1、 求一个矩阵中的两个数,要求两个数不在一行一列,使得这两个数的乘积最大,输出最大积。直接暴力,5分钟做完
//矩阵 public class 题目1 { public static void main(String[] args){ Scanner scanner = new Scanner (System.in); int n=scanner.nextInt (); int m = scanner.nextInt (); int a[][] = new int[n][m]; int max = Integer.MIN_VALUE; for (int i=0;i<a.length;i++){ for (int j=0;j<a[i].length;j++){ a[i][j] = scanner.nextInt (); } } for (int i=0;i<a.length;i++){ for (int j=0;j<a[i].length;j++){ for (int x=0;x<a.length;x++){ for (int y = 0;y<a[x].length;y++){ if (x!=i&&y!=j) { int sum = a[i][j] * a[x][y]; if (sum > max) { max = sum; } } } } } } System.out.println (max); } }2、按给定排序方法给数组排序,这道题花了我一个半小时的时间,将归并、快排、希尔、插入、选择、堆排都调试了一遍,最后感觉归并最像给出的结果集,不知道是不是归并
public static void main(String[] args){ Scanner scanner = new Scanner (System.in); int n = scanner.nextInt (); int a[] = new int[n]; for (int i=0;i<a.length;i++){ a[i] =scanner.nextInt (); } mergeSort (a,0,a.length-1); for (int i=0;i<a.length;i++){ System.out.print (a[i]+" " ); } } private static void mergeSort(int[] a, int left, int right) { if (left>=right){ return; } int mid = (left+right)>>>1; mergeSort (a,left,mid); mergeSort (a,mid+1,right); merge(a,left,mid,right); } private static void merge(int[] a, int left, int mid, int right) { int s1 = left; int s2 = mid+1; int res[] = new int[right-left+1]; int i=0; while (s1<=mid&&s2<=right){ if (a[s1]<=a[s2]){ res[i++] = a[s1++]; }else { res[i++] = a[s2++]; } } while (s1<=mid){ res[i++] = a[s1++]; } while (s2<=right){ res[i++] = a[s2++]; } for (int j=0;j<res.length;j++){ a[j+left] = res[j]; } }3、给定一个数字,求转化为二进制后1的个数,没啥好说的五分钟
public static void main(String[] args){ Scanner scanner = new Scanner (System.in); Long num = scanner.nextLong (); String s = Long.toString (num, 2); String s1 = s.replaceAll ("0", ""); System.out.println (s1.length ()); }4、将字符串向左移位n个,比如hellowrold向左移位5个,变成worldhello,没啥好说的10分钟,一开始的时候没有考虑到n可能大于字符串长度的情况,耽误了点时间
public static void main(String[] args){ Scanner scanner = new Scanner (System.in); String s1 = scanner.nextLine (); int n = scanner.nextInt (); if (n>=s1.length ()){ n = n%s1.length (); } char c1 [] = new char[n]; char c2 [] = new char[s1.length ()-n]; for (int i=0;i<s1.length ();i++){ if (i<n){ c1[i] = s1.charAt (i); }else { c2[i-n] = s1.charAt (i); } } System.out.println (new String (c2)+new String (c1) ); }
全部评论
(13) 回帖