哈希表和双指针

80 阅读1分钟

Day01 n数之和

1、两数之和

  • 思路
    • O(n^2) 循环遍历
    • O(n) 哈希表
  • 题解
    class Solution {
    public int[] twoSum(int[] nums, int target) {
      int[] result = new int[2];
    
      return result;
    }
    public int[] twoSum1(int[] nums, int target) {
      int[] result = new int[2];
      for (int i = 0; i < nums.length; i++) {
         for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] + nums[i] == target){
               result[0] = i;
               result[1] = j;
            }
         }
      }
      return result;
    }
    }
    

2、三数之和

  • 思路
    • for循环+hash遍历
    • 双指针解法
  • 题解
    class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        //双指针移动、重复结果集过滤
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) return ans;
            //重复性过滤!!!注意思考
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0){
                    right --;
                }else if (sum < 0){
                    left ++;
                }else {
                    ans.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    while (left < right && nums[left + 1] == nums[left]) left ++;
                    while (right > left && nums[right - 1] == nums[right]) right --;
                    right --;
                    left ++;
                }
            }
        }
        return ans;
     }
    }