一、二分查找
public static int search(int[] nums, int target) { int left = 0, right = nums.length-1; while (left <= right){ int mid = (left + right)/2; if (nums[mid] > target){ right = mid - 1; }else if (nums[mid] < target){ left = mid + 1; }else { return mid; } } return -1; }
二、两数之和、三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
// 两束之和 public int[] twoSum(int[] nums, int target) { int[] two = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++) { if (nums[i]+nums[j] == target){ two[0] = nums[i]; two[1] = nums[j]; } } } return two; } } // 三数之和为0 class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); Set<List<Integer>> set = new HashSet<>(); for(int i=0;i<nums.length;i++){ if(nums[i]>0)break; int target = -nums[i]; int left = i+1; int right = nums.length-1; while(left < right){ if(target < nums[left] + nums[right]){ right--; }else if(target > nums[left] + nums[right]){ left++; }else{ set.add(Arrays.asList(nums[i], nums[left], nums[right])); left++; } } } return new ArrayList<>(set); } }
三、给定一个数,要求输出对应位数的n进制的数
两种方法
// Integer.toString(num, 7) public String convertToBase7(int num, n) { return Integer.toString(num, n); } // StringBuilder 加入 为7进制 public String convertToBase7(int num) { StringBuilder sb = new StringBuilder(); if (num == 0) return "0"; boolean flag = num < 0; num = Math.abs(num); while (num != 0) { sb.append(num % 7); num /= 7; } if (flag) sb.append("-"); return sb.reverse().toString(); }