classSolution{ public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); int n = nums.length; if (n<3) return res; Arrays.sort(nums); for (int i=0; i<n-2; i++) { if (nums[i]>0) break;//最小的数必须小于等于0才能使和为0 if (i>0 && nums[i-1]==nums[i]) continue;//避免重复 int j = i+1, k = n-1; while (j<k) { int sum = nums[i]+nums[j]+nums[k]; if (sum==0) { res.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[j], nums[k]))); while (j<k && nums[j]==nums[++j]); while (j<k && nums[k]==nums[--k]); } elseif (sum<0) { while (j<k && nums[j]==nums[++j]); } else { while (j<k && nums[k]==nums[--k]); } } } return res; } }
classSolution{ publicintlongestConsecutive(int[] nums){ HashMap<Integer, Integer> map = new HashMap<>(); int res = 0; for (int num: nums) { if (map.containsKey(num)) continue; int left = map.getOrDefault(num-1, 0); int right = map.getOrDefault(num+1, 0); int len = left+right+1; map.put(num, len); map.put(num-left, len); map.put(num+right, len); res = Math.max(res, len); } return res; } }
classSolution{ publicbooleansearchMatrix(int[][] matrix, int target){ int i = matrix.length-1; int j = 0; while (i>=0 && j<matrix[0].length) { if (matrix[i][j]==target) returntrue; elseif (matrix[i][j]>target) i--; else j++; } returnfalse; } }
classSolution{ publicintfindDuplicate(int[] nums){ int fast = 0, slow = 0; while (true) { fast = nums[nums[fast]]; slow = nums[slow]; if (fast==slow) break; } fast = 0; while (true) { fast = nums[fast]; slow = nums[slow]; if (fast==slow) break; } return slow; } }
classSolution{ public List<Integer> findDisappearedNumbers(int[] nums){ for (int i=0; i<nums.length; i++) { int index = Math.abs(nums[i])-1; if (nums[index]>0) { nums[index] *= -1; } } List<Integer> res = new ArrayList<>(); for (int i=0; i<nums.length; i++) { if (nums[i]>0) res.add(i+1); } return res; } }
classSolution{ publicintsubarraySum(int[] nums, int k){ int res = 0, sum = 0; HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for (int num: nums) { sum += num; if (map.containsKey(sum-k)) { res += map.get(sum-k); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return res; } }
classSolution{ publicintfindUnsortedSubarray(int[] nums){ int max = nums[0], min = nums[nums.length-1]; int left = 0, right = -1; for (int i=0; i<nums.length; i++) { if (nums[i]>=max) max = nums[i]; else right = i; if (nums[nums.length-1-i]<=min) min = nums[nums.length-1-i]; else left = nums.length-1-i; } return right-left+1; } }
classSolution{ publicintleastInterval(char[] tasks, int n){ int[] count = newint[26]; for (char c: tasks) { count[c-'A']++; } Arrays.sort(count); int most = count[25]; int last = 1; for (int i=24; i>=0; i--) { if (most==count[i]) last++; elsebreak; } int res = (n+1) * (most-1) + last; return Math.max(res, tasks.length); } }