classSolution { public void moveZeroes(int[] nums) { int n = nums.length;
int lp = 0; int rp = lp;
while(lp != n - 1){ if(nums[lp] == 0){ while(rp != n){ if(nums[rp] != 0){ int tmp = nums[rp]; nums[rp] = nums[lp]; nums[lp] = tmp; break; } rp += 1; } } lp += 1; rp = lp; } } }
11.盛最多水的容器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Solution { public int maxArea(int[] height) { intn = height.length; intleft = 0; intright = n - 1;
int area = 0; while(left < right){ int h = Math.min(height[left], height[right]); area = Math.max(area, h * (right - left)); if(height[left] < height[right]){ left ++; }else{ right -- ; } } return area; } }
class Solution { public List<List<Integer>> threeSum(int[] nums) { //首先先排序(升序) List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); int n = nums.length;
for(int i = 0; i < n; i++){ if(nums[i] > 0){ return result; }
class Solution { public int lengthOfLongestSubstring(String s) { intn = s.length(); if(n == 0) return 0; if(n == 1) return 1;
intleft = 0; intright = 1;
int result = 0; while(left < n - 1){ Map<Character, Integer> map = new HashMap<>(); map.put(s.charAt(left), left); while(right < n && !map.containsKey(s.charAt(right))){ map.put(s.charAt(right), right); right++; } result = Math.max(result, right - left); left = left + 1; right = left + 1; } return result; } }
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int sum = 0; int result = 0; map.put(0, 1); for(int i = 0;i < nums.length;i++){ sum += nums[i];
//暴力解法 class Solution { public int removeElement(int[] nums, intval) { int n = nums.length; for(int i = 0; i < n; i ++){ if(nums[i] == val){ for(int j = i + 1; j < n; j++){ nums[j - 1] = nums[j]; } i--; n--; } } return n; } }
//快慢指针法 class Solution { public int removeElement(int[] nums, intval) { int n = nums.length; int slow = 0; for(int fast = 0; fast < n; fast ++){ if(nums[fast] != val){ nums[slow++] = nums[fast]; } } return slow; } }
26.删除有序数组中的重复项
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//快慢指针 class Solution { public int removeDuplicates(int[] nums) { Map<Integer, Integer> dict = new HashMap<>(); int slow = 0; for(int fast = 0; fast < nums.length;fast++){ if(!dict.containsKey(nums[fast])){ nums[slow++] = nums[fast]; dict.put(nums[fast], 0); } } return slow; } }