[算法]兩數之和,三數之和

1. 兩數之和

給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。數組

你能夠假設每一個輸入只對應一種答案,且一樣的元素不能被重複利用。spa

示例:指針

給定 nums = [2, 7, 11, 15], target = 9

由於 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]

LeetCode:https://leetcode-cn.com/problems/two-sum/description/code

思路:blog

兩層for循環時間複雜度是O(N)的想法你們應該都會,想一想有沒有時間複雜度更低的解法呢?排序

答案就是利用hashmap,這樣能夠用hashmap的key記錄差值,value記錄下標,在hashmap中進行查找的時間複雜度是O(1),這樣總的時間複雜度是O(N)。three

class Solution {
    public int[] twoSum(int[] a, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < a.length; i++) {
            if(map.containsKey(a[i])){
                res[0] = map.get(a[i]);
                res[1] = i;
            }
            map.put(target - a[i], i);
        }
        return res;
    }
}

2. 三數之和

給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出全部知足條件且不重複的三元組。ip

注意:答案中不能夠包含重複的三元組。leetcode

例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],

知足要求的三元組集合爲:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

LeetCode:https://leetcode-cn.com/problems/3sum/description/get

思路:

讓時間複雜度儘量小,先排序,時間複雜度能夠是O(NlogN),而後用三個指針遍歷一次便可,這樣總的時間複雜度是O(NlogN)。

固然也能夠參考上道題,讓hashmap進行記錄,這樣的話,須要記錄兩個值的組合,時間複雜度仍是O(N^2)。

public List<List<Integer>> threeSum(int[] nums) {
        if(nums == null){
            return null;
        }
        if(nums.length < 3){
            return new ArrayList<>();
        }
        
        Arrays.sort(nums);
        HashSet<List<Integer>> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            int j = i + 1;
            int k = nums.length - 1;
            while(j < k){
                if(nums[i] + nums[j] + nums[k] == 0){
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    set.add(list);
                    while(j < k && nums[j] == nums[j + 1]){
                        j++;
                    }
                    while(j < k && nums[k] == nums[k - 1]){
                        k--;
                    }
                    j++;
                    k--;
                }else if(nums[i] + nums[j] + nums[k] < 0){
                    j++;
                }else{
                    k--;
                }
            }
        }
        return new ArrayList<>(set);
    }
相關文章
相關標籤/搜索