Two Sum

       歡迎來到LeetCode的世界,本人程序員一枚,灰常菜的那種,目前處於找工作時期,正在刷LeetCode上的題目,希望通過自己寫博客能記下自己的思路與成長,也希望能幫助到有需要的朋友。由於本人非大神,如果有什麼問題,還希望能多多指正,謝謝啦!
       如果有和我也在忙着找工作的小夥伴呢,希望咱們可以多多交流呀,一起加油吧!
       閒話不多說,咱們進入LeetCode的題目吧!
題目:Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

       最早出現在我腦海裏的思路,那就是遍歷數組,因爲要找出兩個數的和等於target的所在數組的位置,所以要有兩個for循環,那麼第一個代碼就出來了:

public int[] twoSum(int[] nums, int target) {
    int[] index = new int[2];
    for(int i=0;i<nums.length-1;i++){
        for(int j=i+1;j<nums.length;j++){
            if(target ==nums[i] +nums[j]){
                index[0] = i;
                index[1] = j;
            }
        }
    }
    return index;
}

       這道題這樣寫在LeetCode上也可以編譯通過,並且Accepted,但可以看到它的運行時間Runtime: 444 ms,運行結果顯示的是Your runtime beats 30.62% of java coders,也就是說其實這道題還有其他解,並且比當前運行時間要小很多,那麼我們分析一下,上面的代碼總體時間複雜度其實是O(n2),這樣的時間複雜度是很可怕的,不到玩不得以還是不要寫出這種時間複雜度的代碼,而且面試官看到這種代碼,我想只有被拒的可能性了!那麼有沒有更優的解決辦法呢?
       其實用過Map的小夥伴,可以很快想到可以用map,因爲map的查詢操作的時間複雜度是O(1),在這種可以用HashMap(這也是很多互聯網公司常考的數據結構),代價是用空間換取時間。其實很難說是不是最優解,不過從運行時間上來說,比第一種較爲暴力的遍歷要好很多。
       如果用HashMap的話,key很容易想到用nums[]數組中的值,那麼value值呢?因爲此題要求返回的是index,因此可以讓value存儲index,請看下面這段代碼:(本段代碼實看了LeetCode上的部分代碼再寫的)

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

       LeetCode顯示Accepted,查看運行時間,Runtime: 332 ms,Your runtime beats 92.04% of java coders.這樣的代碼就很優秀了!今天就先到這,明天咱們接着聊吧!~_~

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