第三週 Two Sum

Two Sum

Leetcode algorithms problem 1: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.

  • 例子

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

  • 思路

    兩個循環,第一個循環遍歷整個給定數組,第二個循環遍歷第一個循環當前下標往後的數,當補碼存在即返回結果下標。

代碼

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> two(2);
        int count = nums.size();
        int begin = 0;
        int temp;
        for(begin; begin < count; begin++) {
            two[0] = begin;
            temp = target - nums[begin];
            for(int i = begin + 1; i < count; i++) {
                if(temp == nums[i]) {
                    two[1] = i;
                    return two;
                }
            }
        }
    }
};

時間複雜度: O(n^2)
空間複雜度: O(1)


收穫&雜談

繼續刷了道簡單題找找感覺,這道two sum還是挺簡單的,沒有複雜度的限制,一開始的思路就可以通過,一些細節一開始沒想好導致一開始沒通過,debug後成功通過。
查看答案,發現自己的代碼少了錯誤報告語句
throw new IllegalArgumentException(“No two sum solution”);
以及一個解決思路提供了利用map.containsKey這個成員函數來降低時間複雜度,降爲了O(n),同時空間複雜度上升爲O(n)。

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