无重复字符最长子串
输入: s = "abcabcbb"输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
//匹配元素可能在最长无重复字符串中也可能没有。 即有可能会出现小于left边界的情况class Solution { public int lengthOfLongestSubstring(String s) { if(s.length() == 0) return 0; if(s.length() == 1) return 1; HashMap<Character, Integer> map = new HashMap(); int left = 0; int max = 0; for(int i = 0; i < s.length(); i++){ if(map.containsKey(s.charAt(i))){ left = Math.max(left, map.get(s.charAt(i))+1); } map.put(s.charAt(i), i); max = Math.max(max, i-left+1); } return max; }}
盛水最多的容器

输入:[1,8,6,2,5,4,8,3,7]输出:49 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
//双指针 容积为 左右最低高度*(右-左)class Solution { public int maxArea(int[] height) { int left = 0; int right = height.length-1; int res = 0; int temp = 0; while(left < right){ temp = height[left] > height[right] ? (right-left)*height[right--]: (right-left)*height[left++]; res = Math.max(res, temp); } return res; }}
接雨水

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]输出:6解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
class Solution {public int trap(int[] height) { int left = 0, right = height.length - 1; int ans = 0; int left_max = 0, right_max = 0; while (left < right) { if (height[left] < height[right]) { if (height[left] >= left_max) { left_max = height[left]; } else { ans += (left_max - height[left]); } ++left; } else { if (height[right] >= right_max) { right_max = height[right]; } else { ans += (right_max - height[right]); } --right; } } return ans;}}
三数之和
输入:nums = [-1,0,1,2,-1,-4]输出:[[-1,-1,2],[-1,0,1]]
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> res = new ArrayList(); for (int k = 0; k < nums.length - 2; k++) { if(nums[k] > 0) break; if(k > 0 && nums[k] == nums[k - 1]) continue; int i = k + 1; int j = nums.length - 1; while(i < j) { int sum = nums[k] + nums[i] + nums[j]; if(sum < 0) { while(i < j && nums[i] == nums[++i]); } else if(sum > 0) { while(i < j && nums[j] == nums[--j]); } else { res.add(new ArrayList<Integer>(Arrays.asList(nums[k], nums[i], nums[j]))); while(i < j && nums[i] == nums[++i]); while(i < j && nums[j] == nums[--j]); } } } return res; }}
合并两个有序数组
输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3输出:[1,2,2,3,5,6]解释:需要合并 [1,2,3] 和 [2,5,6] 。合并结果是 [1,2,2,3,5,6] ,其中斜体加粗标注的为 nums1 中的元素。
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m - 1; int j = n - 1; int end = m + n - 1; while (j >= 0) { nums1[end--] = (i >= 0 && nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--]; } }}
颜色分类