Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

自己的思路:數組先排序,然後從兩頭開始找,藉助HashMap存儲數組的值到索引的映射。

時間複雜度:o(n * log(n)) 排序部分

public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int len = nums.length;
        //利用HashMap記錄數組的值到索引的映射
        //重複的key,HashMap會覆蓋,對於兩個相同的數即爲所求,則輸出的索引會出錯 [3,3] 6 如果不做處理,則輸出[1,1]
        //存入HashMap的過程中進行key判斷
        HashMap<Integer, Integer> value2index = new HashMap<Integer, Integer>(len);
        for(int i = 0; i < len; i++){
            int num = nums[i];
            if(value2index.containsKey(num)){
                if(num + num == target){
                    result[0] = value2index.get(num);
                    result[1] = i;
                    return result;
                }
            }else{
                value2index.put(num, i);
            }
        }
        Arrays.sort(nums);
        int low = 0, high = len - 1;
        while(low < high){
            int sum = nums[low] + nums[high];
            if(sum == target){
                result[0] = value2index.get(nums[low]);
                result[1] = value2index.get(nums[high]);
                return result;
            }else{
                if(sum < target){
                    low ++;
                }else{
                    high --;
                }
            }
        }  
        return null;
    }

 

別人的思路:遍歷數組,當遍歷到一個數的時候,查找另外所需的數是否在數組中(利用hashmap存儲值到索引的映射)

時間複雜度:o(n)

public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int len = nums.length;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(len);
        for(int i = 0; i<len; i++){
            int numToFind = target - nums[i];
            if(map.containsKey(numToFind)){
                result[0] = map.get(numToFind);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return null;
        
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章