public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nums = sc.nextInt(); for (int i = 0; i<nums; i++){ int N = sc.nextInt(); maxandmin(N); } } public static void maxandmin(int N){ if (N==1||N==2){ System.out.println("1 1"); //如果n是1或者2就输出 1 1 return; } //之后每4个一组 0011 int min = getmin(N); int max = N-getmin(N-1); System.out.println(min + " " + max); } public static int getmin(int N){ int temp = (N-2)%4; //temp临时值接住 if (temp==1 || temp==2){ return 0; } else return 1; } }
结果
多多的电子字典
题目
分析
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); //n个a int m=input.nextInt(); //m个b int k=input.nextInt(); //第k小的单词 System.out.println(dik(n,m,k)); }
public static String dik(int n,int m,int k){ String res="123";
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.nextLine(); //一定要用nextLine() 因为字符串有空格!!!!!! System.out.println(replaceSpace(s)); //调用方法返回结果 }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println("递归:"+fib(n)); System.out.println("动态规划:"+fiber(n)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); /*for (int i = 0; i < n; i++) { a[i]=input.nextInt(); }*/ System.out.println("递归:"+numWays(n)); System.out.println("动态规划:"+numWayser(n)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i < n; i++) { a[i]=input.nextInt(); } System.out.println(minArray(a)); }
//排序输出 public static int minArray(int[] numbers) { Arrays.sort(numbers); //排序 return numbers[0]; //输出最小的第一位 }
//二分法 public static int minArray(int[] numbers) { int i=0; //左指针 int j=numbers.length-1; //右指针 while(i<j){ int z=(i+j)/2; //找中间位置 if(numbers[z]>numbers[j]){ i=z+1; //min值在右边出现 }else if(numbers[z]<numbers[j]){ j=z; //min值在左边出现 }else { j--; //无法确定范围 缩小范围继续找 } } return numbers[i]; }
//board是要找的路径集合 words字符串转的字符数组 i和j是board下标 k是找到了几个 private static boolean dfs(char[][] board, char[] words, int i, int j, int k) { if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != words[k]){ return false; // i和j越界 / 找不到符合 } if(k == words.length - 1) { //已经全部找到了!!! return true; } char temp=board[i][j]; //中间值 board[i][j]='/'; //用过之后改成 ‘/’ //上下左右都找找 boolean res=dfs(board, words, i + 1, j, k + 1) || dfs(board, words, i - 1, j, k + 1) || dfs(board, words, i, j + 1, k + 1) || dfs(board, words, i , j - 1, k + 1); board[i][j]=temp; //用完之后再回溯返回原值 return res; }
}
结果
机器人的运动范围
题目
分析
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int m=input.nextInt(); int n=input.nextInt(); int k=input.nextInt(); System.out.println(movingCount(m,n,k)); }
public static int movingCount(int m, int n, int k) { int res=123; return res; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int m=input.nextInt(); System.out.println(cuttingRope(m)); }
public static int cuttingRope(int n) { if(n<=3){ return n-1; } int a=n/3; int b=n%3; if(b==0){ return (int)Math.pow(3,a); } if(b==1){ return (int)Math.pow(3,a-1)*4; } return (int)Math.pow(3,a)*2; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int m=input.nextInt(); System.out.println(cuttingRope(m)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int m=input.nextInt(); System.out.println(hammingWeight(m)); }
public static int hammingWeight(int n) { int res=0; //接最后结果 while(n!=0){ res++; n=n&(n-1); //消除数字n最右边的1 } return res; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); System.out.println(isNumber(s)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i < a.length; i++) { a[i]=input.nextInt(); } System.out.println(Arrays.toString(exchange(a))); }
public static int[] exchange(int[] nums) { int i=0; //左指针 int j=nums.length-1; //右指针 int temp=0; //临时交换用 while(i<j) { while (i < j && ((nums[i] % 2) != 0)) { i++; //奇数往后移动 } while (i < j && ((nums[j] % 2) == 0)) { j--; //偶数往前移动 } //左边是偶数 右边是奇数的话就交换 temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } return nums; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[][] a=new int[][]{{1,2,3},{4,5,6},{7,8,9}}; System.out.println(Arrays.toString(spiralOrder(a))); }
public static int[] spiralOrder(int [][] matrix) { if(matrix.length == 0) { return new int[0]; //数组空就弹出空数组 } int row=matrix.length; //行 int col=matrix[0].length; //列 int left=0; //二维数组上面行的最左边 int right=col-1; //二维数组上面行的最右边 int top=0; //二维数组左边的最上边 int bottom=row-1; //二维数组左边的最下边 int[] a=new int[row*col]; int q=0; //控制结果数组下标 while(left<=right&&top<=bottom){ //从左到右 for(int i=left;i<=right;i++){ a[q++]=matrix[top][i]; //top行 } //从上到下(从下一行开始向下走) for(int i=top+1;i<=bottom;i++){ a[q++]=matrix[i][right]; //right列 } //从右到左(从左边一列开始向左走) if(top!=bottom) { //如果是一行的话就不需要返回去(已经左到右) for (int i=right-1;i>=left;i--) { a[q++]=matrix[bottom][i]; //bottom行 } } //从下到上(从上一行开始向上走) if(left!=right) { //如果是一列的话就不需要返回去(已经上到下) for (int i=bottom-1;i>top;i--) { a[q++]=matrix[i][left]; //left列 } } //下一个正方形矩阵(往里缩小 -- 变换四个下标) top++; right--; left++; bottom--; } return a; //返回a数组 }
class MinStack { Stack<Integer> A, B; public MinStack() { A = new Stack<>(); B = new Stack<>(); } public void push(int x) { A.add(x); if(B.empty() || B.peek() >= x) B.add(x); } public void pop() { if(A.pop().equals(B.peek())) B.pop(); } public int top() { return A.peek(); } public int min() { return B.peek(); } }
public class ErChaShu { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i < n; i++) { a[i]=input.nextInt(); } System.out.println(verifyPostorder(a)); }
public static boolean verifyPostorder(int[] postorder) { return recur(postorder, 0, postorder.length - 1); // 调用方法( 数组postorder i j ) }
public static boolean recur(int[] postorder, int i, int j) { if(i >= j){ return true; //子树节点<=1 肯定true } //找左子树 int chang = i; while(postorder[chang] < postorder[j]){ //左边肯定比根节点小(第一个大的数字就是右节点的开始位置) chang++; } //找右子树 int zhong = chang; //找到第一个 > postorder[j]的值就是右子树的开始位置 while(postorder[chang] > postorder[j]) { //右边肯定都比根节点大 chang++; }
//1. 按位拆除判断(超时) public static int countDigitOne(int n) { int res=1; if(n==0){ //0的话出现0次 res=0; } if(n==1){ //1的话出现1次 res=1; } for(int i=2;i<=n;i++){ //从2开始 res+=jige(i); } return res; } //统计1的次数 public static int jige(int i){ int sum=0; while(i!=0){ //缩小范围到0 if(i%10==1){ sum++; //出现1的时候计数器+1 } i=i/10; //不断缩小 } return sum; }
//2. 数学归纳法 public int countDigitOne(int n) { int res = 0; for (long m = 1; m <= n; m *= 10) { long a = n / m; long b = n % m; res += (a + 8) / 10 * m + (a % 10 == 1 ? b + 1 : 0); } return res; }
结果
数字序列中某一位的数字(数学归纳)
题目
分析
1. 第一个while用来判断多少个
2. 用char数组存放结果,然后不断地取出到哪一位
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public static int findNthDigit(int n) { int res=0; if(n<10){ return n; //前10位是按照顺序0123456789 } int i=1; while(n>i*(Math.pow(10,i-1)*9)){ // 9(10个) 99(90个) 999(900个) n-=i*Math.pow(10,i-1)*9; i++; } char[] result=String.valueOf((int)Math.pow(10,i-1)+(n-1)/i).toCharArray();//我们用字符串来接收值,方便找位数 result结果为我们要的那个数的 int value=result[(n-1)%i]-'0'; //(n-1)%位数 得出我们要的第x位的数 return value; }
class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); int ans = 0; Map<Character, Integer> map = new HashMap<>();//key出现的字符,value对应的最新的位置 // try to extend the range [i, j] int start=0; for (int end = 0; end < n; end++) { if (map.containsKey(s.charAt(end))) { start = Math.max(map.get(s.charAt(end)) + 1, start);//由于重复的坐标不知道在start的前方还是后方,所以要取个最大值 } ans = Math.max(ans, end - start + 1); //更新最大长度 map.put(s.charAt(end), end); //存放的字符对应位置更新 } return ans; } }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(nthUglyNumber(n)); //调用方法 }
public static int nthUglyNumber(int n) { int p2=0; //只乘2 int p3=0; //只乘3 int p5=0; //只乘5 int[] dp=new int[n]; //存放所有的丑数 dp[0]=1; //第一个丑数是1 for(int i=1;i<n;i++){ dp[i]=Math.min(dp[p2]*2,Math.min(dp[p3]*3,dp[p5]*5)); //从第二位开始求当前位置丑数 //看是哪个指针走了就跳后面 if(dp[i]==dp[p2]*2){ p2++; } if(dp[i]==dp[p3]*3){ p3++; } if(dp[i]==dp[p5]*5){ p5++; } } return dp[n-1]; //最后返回n-1结果 } }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); System.out.println(firstUniqChar(s)); }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] a = new int[]{10,26,30,31,47,60}; int target=input.nextInt(); System.out.println(Arrays.toString(twoSum(a,target))); }
public static int[] twoSum(int[] nums, int target) { int i = 0, j = nums.length - 1; //定义两个指针 while(i < j) { int s = nums[i] + nums[j]; //求和 if(s < target){ i++; //太小了往后挪 } else if(s > target){ j--; //太大了往前挪 } else return new int[]{nums[i], nums[j]}; //找到了就返回这两个值 } return new int[0]; //默认返回空 }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int target=input.nextInt(); System.out.println(findContinuousSequence(target)); }
public static int[][] findContinuousSequence(int target) { int i = 1; // 滑动窗口的左边界 int j = 1; // 滑动窗口的右边界 int sum = 0; // 滑动窗口中数字的和 //res集合接收结果 List<int[]> res = new ArrayList<>(); while(i<=target/2){ //只能到一半的位置 if(sum<target){ sum+=j; //太小了 往右移动找新的 j++; }else if(sum>target){ sum-=i; //太大了 往右移动把最左边的删除 i++; }else{ //找到了结果集 int[] arr=new int[j-i]; //长度是j-i for(int k=i;k<j;k++){ arr[k-i]=k; //要把i和j开始遍历放入数组 } //将每一个结果数组放入res集合 res.add(arr); //左边界限向右移动(找到了i就要往后挪动) sum-=i; //sum要减去i i++; } } return res.toArray(new int[res.size()][]); //集合转数组 }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); //nextLine()输入格式 System.out.println(reverseWords(s)); }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); int n=input.nextInt(); System.out.println(reverseLeftWords(s,n)); }
Queue<Integer> queue; LinkedList<Integer> max; public MaxQueue() { queue = new LinkedList<>(); max = new LinkedList<>();//LinkedList是双端链表 } public int max_value() { return max.size()==0?-1:max.getFirst(); } public void push_back(int value) { queue.add(value); while(max.size()!=0&&max.getLast()<value){//注意:这里第二个判断条件不能带等号,即max中对于当前queue中的具有相同值的元素会全部存储,而不是存储最近的那个。 max.removeLast(); } max.add(value); } public int pop_front() { if(max.size()!=0&&queue.peek().equals(max.getFirst()))//Integer类型的值的比较不能直接使用== max.removeFirst(); return queue.size()==0?-1:queue.poll(); } }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int m=input.nextInt(); System.out.println(lastRemaining(n,m)); }
public static int lastRemaining(int n, int m) { //新建list集合 ArrayList<Integer> list = new ArrayList<>(); //将所有元素都加入list集合 for (int i=0;i<n;i++){ list.add(i); } //定义下标--确定每次删除的位置 int i=0; //循环删除 while(n>1){ i=(i+m-1)%n; list.remove(i); //list删除 n--; //总数减少1个 } return list.get(0); //剩下的唯一一个数字 }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] a=new int[]{7,1,5,3,6,4}; System.out.println(maxProfit(a)); }
public static int maxProfit(int[] prices) { if(prices.length==0){ return 0; //数组长为0 } int min=prices[0]; //购买的日子 int[] dp=new int[prices.length]; //存每个位置的利润 for (int i=1;i<prices.length;i++) { min=Math.min(min,prices[i-1]); //找最小值 dp[i]=Math.max(dp[i-1],prices[i]-min); //每个位置的利润 } return dp[prices.length-1]; }
}
结果
求1+2+..+n的和(归纳)
题目
分析
1. 递归
2. 迭代
3. 数学归纳法
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(sumNums(n)); }
public static int sumNums(int n) { int res=0; res=((n+1)*n)/2; return res; }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int m=input.nextInt(); System.out.println(add(n,m)); }
public static int add(int a, int b) { while(b!=0){ int tempSum=a^b; //求不考虑进位的相加和 int carrySum=(a&b)<<1; //进位的和 //不断循环迭代 直到没有进位(b==0) a=tempSum; b=carrySum; } return a; }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] a=new int[]{1,2,3,4,5}; System.out.println(Arrays.toString(constructArr(a))); }
public static int[] constructArr(int[] a) { if(a.length==0){ return new int[0]; //返回0 } int[] b=new int[a.length]; b[0]=1; int temp=1; //计算左下角 for(int i=1;i<a.length;i++){ //从上到下 b[i]=b[i-1]*a[i-1]; } //计算右上角 for(int i=a.length-2;i>=0;i--){ //从下往上 temp=temp*a[i+1]; b[i]=b[i]*temp; }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); System.out.println(strToInt(s)); }
public class HuiWen { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); //可以输入空格 System.out.println(isPalindrome(s)); }
public static boolean isPalindrome(String s) { StringBuilder sb=new StringBuilder(); int len=s.length(); for(int i=0;i<len;i++){ if(s.charAt(i)>='0'&&s.charAt(i)<='9'||s.charAt(i)>='a'&&s.charAt(i)<='z'){ sb.append(s.charAt(i)); } if(s.charAt(i)>='A'&&s.charAt(i)<='Z'){ sb.append((char)(s.charAt(i)+32)); } } int left=0; int right=sb.length()-1; while(left<right){ if(sb.charAt(left)==sb.charAt(right)){ left++; right--; }else{ return false; } } return true; }
public class WuChongFuZiChuan { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); System.out.println(lengthOfLongestSubstring(s)); }
public static int lengthOfLongestSubstring(String s) { int n = s.length(); //获取字符串长度 int ans = 0; Map<Character, Integer> map = new HashMap<>(); int start=0; for (int end = 0; end < n; end++) { char a = s.charAt(end); //获取当前位置字符 if (map.containsKey(a)) { start = Math.max(map.get(a), start); } ans = Math.max(ans, end - start + 1); //算距离 map.put(s.charAt(end), end + 1); //当前map里面存当前字符串字符和下标 } return ans ; }
public class FanZhuan { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(reverse(n)); }
public static int reverse(int n) { int res=0; //最后结果 String temp=""; //整数转字符串 反转之后的结果 if(n>0){ temp=new StringBuilder(String.valueOf(n)).reverse().toString(); }else{ temp="-"+new StringBuilder(String.valueOf(n).substring(1)).reverse().toString(); //从第二个位置开始 第一个是-号 } if(temp.equals("")){ temp = "0"; //n为0 }
class Solution { public int romanToInt(String s) { int sum = 0; int preNum = getValue(s.charAt(0)); for(int i = 1;i < s.length(); i ++) { int num = getValue(s.charAt(i)); if(preNum < num) { sum -= preNum; } else { sum += preNum; } preNum = num; } sum += preNum; return sum; } private int getValue(char ch) { switch(ch) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } }
public class LuoMa { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); String[] strs=new String[n]; for(int i=0;i<n;i++){ strs[i]=input.next(); } System.out.println(longestCommonPrefix(strs)); }
public class ShengKuoHao { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(generateParenthesis(n)); }
public static List<String> generateParenthesis(int n) { List<String> res=new ArrayList<>(); if (n == 0) { return res; //长度为0返回空 } // 执行深度优先遍历,搜索可能的结果 dfs("", n, n, res); return res; }
public class LiangShuChuFFa { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(countAndSay(n)); }
public static String countAndSay(int n) { String res = "1"; for (int i = 2; i <= n; i++) { StringBuilder temp = new StringBuilder(); for (int j = 0; j <res.length(); j++) { int count = 1; while (j + 1 < res.length() && res.charAt(j) == res.charAt(j + 1)) { //j+1小心越界 count++; //记录出现几次 j++; //下标更新 } temp.append(count).append(res.charAt(j)); //添加某个数出现了多少次 2次2 3次4等等 } res = temp.toString(); //res接上一次的结果 } return res; }
public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n -1;i>=0;i--){ //倒序 if(digits[i] == 9){ digits[i] = 0; //如果当前位置是9 就要变为0 }else{ digits[i]++; //其他数字就直接+1 return digits; //然后返回 } } int[] a = new int [n+1]; //新建数组a存放结果 a[0]=1; //给999这+1增加进位留一位为1 return a; }
结果
X的平方根(二分法)
题目
分析
主要二分法找k的平方是不是小于x,然后二分法找
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution { public int mySqrt(int x) { int l = 0, r = x, ans = -1; //找不到就是-1 while (l <= r) { int mid = l + (r - l) / 2; //中间位置 if ((long)mid * mid <= x) { ans = mid; l = mid + 1; //在右边 } else { r = mid - 1; //在左边 } } return ans; } }
public class Jump { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); //输入字符串 System.out.println(partition(s)); //调用方法获取结果 }
public static List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<>(); //res接受结果 backtrack(res, s, new ArrayList<String>()); //调用方法 return res; }
private static void backtrack(List<List<String>> res, String s, ArrayList<String> tmp) { if (s == null || s.length() == 0) { res.add(new ArrayList<>(tmp)); //如果字符串不存在 就返回tmp新的list集合 [] } for (int i = 1; i <= s.length(); i++) { if (isPalidrome(s.substring(0, i))) { //如果截取的这部分是回文串 tmp.add(s.substring(0, i)); //tmp集合存放s的部分 backtrack(res, s.substring(i, s.length()), tmp); //找i之后的部分 前面的s被tmp集合用了 tmp.remove(tmp.size() - 1); //回溯 } } }
private static boolean isPalidrome(String sb) { int left = 0; //左指针 int right = sb.length() - 1; //右指针 while (left < right) { //左右不碰面 if (sb.charAt(left) != sb.charAt(right)) { return false; //如果左右不相等 就返回false } left++; //向中间靠拢 right--; } return true; }
public class Jump { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(isHappy(n)); }
public static boolean isHappy(int n) { Set<Integer> set=new HashSet<>(); while(n!=1&&!set.contains(n)) { //没出现 set.add(n); //set集合里面添加n n = getNext(n); //调用方法得到新的n } return n == 1; //判断结果是不是1 }
private static int getNext(int n) { int totalSum = 0; while (n > 0) { int d = n % 10; //拆分 n = n / 10; totalSum += d * d; //得到n这个数字每一位最终的结果 } return totalSum; }
public class Jump { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); long res=trailingZeroes(n); //获阶乘的结果 int ge=jige(res); System.out.println(ge); }
public static long trailingZeroes(int n) { long res=0; if(n==0||n==1){ res=1; //0!=1 } if(n==2){ res=2; //2!=2*1=2 }else{ res=trailingZeroes(n-1)*n; } return res; }
private static int jige(long res) { int ge=0; //0的个数 long j=0; while(res!=0){ j=res%10; if(j==0){ ge++; } if(j!=0){ break; } res=res/10; } return ge; }
}
//第二种:得到5的个数
public static int trailingZeroes(int n) { int count = 0; //获取的结果 //一个5提供一个0,一个25提供2个0; while (n > 0) { //n大于0就行 count+=n/5; n=n/5; } return count; }
class Solution { private class LargerNumberComparator implements Comparator<String> { @Override public int compare(String a, String b) { String o1 = a + b; String o2 = b + a; return o2.compareTo(o1); } }
public String largestNumber(int[] nums) { String[] s = new String[nums.length]; for (int i = 0; i < nums.length; i++) { s[i] = String.valueOf(nums[i]); //将对应的数字传到s的字符串数组 } Arrays.sort(s, new LargerNumberComparator()); //排序 if (s[0].equals("0")) { return "0"; //如果有0就返回0 }
String res = new String(); for (String numAsStr : s) { res+= numAsStr; //循环将s数组贴合在字符串res上 }
return res; } }
结果
旋转数组(新建数组放)
题目
分析
1. 新建数组b
2. 通过下标的倾斜存入新的数组b
3. 主函数调用输出
代码
1 2 3 4 5 6 7 8 9
public void rotate(int[] nums, int k) { int[] a = new int[nums.length]; for (int i = 0; i < nums.length; i++) { a[(i + k) % nums.length] = nums[i]; } for (int i = 0; i < nums.length; i++) { nums[i] = a[i]; } }
结果
颠倒二进制位(位运算)
题目
分析
主要基于位运算!!!
代码
1 2 3 4 5 6 7 8 9 10 11 12
public int reverseBits(int n) { int res = 0; int count = 0; while (count < 32) { res <<= 1; //res 左移一位空出位置 res |= (n & 1); //得到的最低位加过来 n >>= 1;//原数字右移一位去掉已经处理过的最低位 count++; } return res; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } moveZeroes(a); System.out.println(Arrays.toString(a)); }
//1.排序之后如果前后一样就重复输出 public static int findDuplicate(int[] nums) { int res=0; Arrays.sort(nums); for (int i = 0; i < nums.length-1; i++) { if(nums[i]==nums[i+1]){ return nums[i]; } } return res; }
//2.二分法 public static int findDuplicate(int[] nums) { int n = nums.length; int l = 1, r = n - 1, ans = -1; while (l <= r) { //左<=右 int mid = (l + r) >> 1; //中间位置 int cnt = 0; for (int i = 0; i < n; ++i) { if (nums[i] <= mid) { cnt++; } } if (cnt <= mid) { l = mid + 1; //重复的在右边 } else { r = mid - 1; //重复的在左边 ans = mid; } } return ans; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } System.out.println(lengthOfLIS(a)); }
public static int lengthOfLIS(int[] nums) { if (nums.length == 0) { return 0; //数组长度为0 } int[] dp = new int[nums.length]; Arrays.fill(dp, 1); //数组都补充1 int res = 0; for (int i = 0; i < nums.length; i++) { for(int j=0;j<i;j++){ if(nums[j] < nums[i]){ //说明可以贴在后面 dp[i] = Math.max(dp[i], dp[j] + 1); } } res = Math.max(res, dp[i]); } return res; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } int amount=input.nextInt(); System.out.println(coinChange(a,amount)); }
public static int coinChange(int[] coins, int amount) { //零钱相当于物品,总金额相当于背包容量 int [] dp=new int[amount+1];//dp[i][j]:对前i个零钱,选若干兑换总金额为j的整钱,最少需要的零钱个数为dp[i][j]
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } System.out.println(increasingTriplet(a)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } int k=input.nextInt(); System.out.println(Arrays.toString(topKFrequent(a,k))); }
public static int[] topKFrequent(int[] nums, int k) { //存放key-value这样的形式 存放每个元素出现次数 Map<Integer,Integer> map=new HashMap<>(); //进行排序 PriorityQueue<Map.Entry<Integer, Integer>> maxheap = new PriorityQueue<>((a,b) -> b.getValue() - a.getValue()); //存放结果的数组 int[] result = new int[k]; for (int i = 0; i < nums.length; i++) { map.put(nums[i],map.getOrDefault(nums[i],0)+1); //遍历存放每个key对应的value } for(Map.Entry<Integer, Integer> m : map.entrySet()){ maxheap.offer(m); //按照键值对放入maxhead中 } //倒序输出k个值就是结果 for(int i = 0; i < k; i++){ result[i] = maxheap.poll().getKey(); } return result; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[][] a=new int[][]{{1,5,9},{10,11,13},{12,13,15}}; int m=input.nextInt(); System.out.println(kthSmallest(a,m)); }
public static int kthSmallest(int[][] matrix, int k) { int res=0; int len=matrix.length; //数组的行和列 int[] a=new int[len*len]; int z=0; for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ a[z++]=matrix[i][j]; } } Arrays.sort(a); //进行排序 return a[k-1]; //返回第8个 }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); System.out.println(firstUniqChar(s)); }
public static int firstUniqChar(String s) { //存放字符出现次数和对应字符(键值对) HashMap<Character, Integer> count = new HashMap<Character, Integer>(); //字符串长度 int n = s.length(); //遍历存入map集合 for (int i = 0; i < n; i++) { char c = s.charAt(i); count.put(c, count.getOrDefault(c, 0) + 1); } //遍历找谁出现次数是1次 for (int i = 0; i < n; i++) { if (count.get(s.charAt(i)) == 1) return i; } return -1; //找不到返回-1 }
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { Map<Integer, Integer> map = new HashMap<>(); //Map<Integer, Integer> map = new HashMap<>(); int res = 0; for(int i = 0;i<A.length;i++){ for(int j= 0;j<B.length;j++){ int sumAB = A[i]+B[j]; if(map.containsKey(sumAB)) map.put(sumAB,map.get(sumAB)+1); else map.put(sumAB,1); } }
for(int i = 0;i<C.length;i++){ for(int j = 0;j<D.length;j++){ int sumCD = -(C[i]+D[j]); if(map.containsKey(sumCD)) res += map.get(sumCD); //增加有这个配对的key的value值 } } return res; }
public class BianWeiArr { public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] a={"eat","tea","tan","ate","nat","bat"}; System.out.println(groupAnagrams(a)); }
class WordsFrequency { Map<String,Integer> recMap = new HashMap<>(); public WordsFrequency(String[] book) { for(int i=0;i<book.length;i++) { if(!recMap.containsKey(book[i])) { recMap.put(book[i],1); }else { recMap.put(book[i], recMap.get(book[i])+1); } } }
public int get(String word) { if(recMap.containsKey(word)) { return recMap.get(word); } return 0; } }
/** * Your WordsFrequency object will be instantiated and called as such: * WordsFrequency obj = new WordsFrequency(book); * int param_1 = obj.get(word); */
public class OnlyOne { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); System.out.println(firstUniqChar(s)); }
public class ShuDuiHe { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for(int i=0;i<a.length;i++){ a[i]=input.nextInt(); } int target=input.nextInt(); System.out.println(pairSums(a,target)); }
public static List<List<Integer>> pairSums(int[] nums, int target) { List<List<Integer>> ans=new LinkedList<>(); Arrays.sort(nums); //对数组进行排序 int start=0; int end=nums.length-1; for(;start<end;){ int sum = nums[start] + nums[end]; if (sum < target) { //要变大一些 start++; } else if (sum > target){ //要变小一些 end--; } else { //刚好符合 List<Integer> list = new LinkedList<>(); //新成立list集合 list.add(nums[start]); //存进去start和end位置的值 list.add(nums[end]); ans.add(list); //最终结果添加list集合 start++; //缩小范围 end--; } } return ans; }
public class SouSuoXuanZhuanArr { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) { a[i]=input.nextInt(); } int target=input.nextInt(); System.out.println(search(a,target)); }
public static int search(int[] arr, int target) { int min=Integer.MAX_VALUE; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); //设置map集合存储 for(int i=0;i<arr.length;i++){ map.put(arr[i],i); //将数组的集合内容和下标存储下去 } if(map.containsKey(target)){ //如果map里面有这个就获取map对应下标 int i=map.get(target); min=Math.min(min,i); //多个出现就得到最小的那个索引 return min; } return -1; //默认找不到就是-1 }