Leetcode1——Two Sum

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書

1. 問題描述

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].

2. 求解

解法一

這個題最簡單也是最容易的就是兩層循環遍歷,這個沒什么可說的,時間復雜度為O(n^2)。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int result[] = new int[2];
        int n = nums.length;
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                int sum = nums[i] + nums[j];
                if(sum == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }
}

Leetcode Accepted,Runtime: 45 ms。

解法二

思考一下,如何進行優化呢?首先,條件為nums[i] + nums[j] = target,已知target和nums[i]的情況下,能不能直接確定nums[j]在數組中是否存在呢?這是可以的,很容易想到map結構,當然數據結構要變換一下,而map的查詢復雜度為O(1),map結構的設計有兩種,要不是key為整數,要不key為整數的索引。由于我們求的是整數的索引,因此應該將key設為整數,value為整數的索引。但key為整數有一個問題就是,如果數組中存在相同整數,則后一個放入的數值會覆蓋前一個,因此需要單獨處理。題目中明確說了一個輸入只有一個解,因此如果出現兩個整數相等的情況,只需要找到另一個數字的索引即可。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int result[] = new int[2];
        int n = nums.length;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < n; i++) {
            int other = target - nums[i];
            map.put(nums[i], i);
            if(map.containsKey(other)) {
                //兩個數字不等情況
                if(other != nums[i]) {
                    //注意順序
                    result[0] = map.get(other);
                    result[1] = i;
                    break;
                }else {
                    //數字相等情況
                    result[0] = i;
                    for(int j = i + 1; j < n; j++) {
                        if(nums[j] == other) {
                            result[1] = j;
                            return result;
                        }
                    }  
                }
            }
        }
        return result;
    }
}

Leetcode Accepted,Runtime: 12 ms。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Given an array of integers, return indices of the two num...
    lemooon閱讀 271評論 0 0
  • 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的...
    mztkenan閱讀 387評論 0 0
  • 分析: 解法一:最容易想到的暴力搜索,兩個循環。時間復雜度:O(n^2)解法二:在解法一的基礎上優化一些,比如可以...
    glassyw閱讀 153評論 0 0
  • 注:最精華的思想是:x = nums[i] dict[x] = i取出第i個數字(以0為開頭),把它的值裝載...
    everfight閱讀 110評論 0 0
  • 1. Two Sum Given an array of integers, returnindicesof th...
    LdpcII閱讀 488評論 0 0