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


1. 兩數之和

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

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重復利用。

示例:

給定 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/

思路:

兩層for循環時間復雜度是O(N)的想法大家應該都會,想想有沒有時間復雜度更低的解法呢?

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

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 ?找出所有滿足條件且不重復的三元組。

注意:答案中不可以包含重復的三元組。

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

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

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

思路:

讓時間復雜度盡可能小,先排序,時間復雜度可以是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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM