LeetCode--Array--Two sum (Easy)

1.Two sum (Easy)

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

solution

題意是給定一個int數組nums和一個整數target,在nums裏面找到兩數之和爲target的數,並返回兩數的數組索引。假定nums數組裏面只有惟一的一組結果,且同一個數字只能使用一次。算法

1.最容易想到的暴力算法,也就是我起初想到的!!!數組

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indices = new int[2];
        for (int i = 0; i < nums.length - 1; i++)
        {
            for (int j = i + 1; j < nums.length; j++)
            {
                if (nums[i] + nums[j] == target)
                {
                    indices[0] = i;
                    indices[1] = j;
                    return indices;
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

2.速度更快的解法,HashMapspa

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> m = new HashMap<Integer,Integer>();
        for (int i = 0; i < nums.length; i++)
        {
            int complement = target - nums[i];
            if (m.containsKey(complement))
                return new int[] {m.get(complement),i};
            m.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

reference
https://leetcode.com/articles/two-sum/code

總結

第一種暴力算法就是先取一個數,而後用這個數依次與後面的每個數相加求和,若和與target相等,則將這兩個數的數組索引加入到一個新的int數組中,而後返回這個int數組。time complexity:O(n^2),space complexity:O(1)索引


第二種使用HashMap的方法起初不太容易想到。基本思路是將數組值做爲鍵,索引做爲值。是先建立一個hashmap,而後遍歷數組nums,若是hashmap中已經存在complement=target-nums[i]這個元素,則將complement鍵對應的值(即數組索引),和i存到一個新的int數組裏面並返回;若果不存在,則將nums[i],i分別做爲鍵與值存到hashmap中去。若是遍歷完數組沒有找到相應的結果,則拋出異常。time complexity:O(n),space complexity:O(n)ci


Notes
1.數組值和下標互換是一種經常使用的技巧,不過只對整數有用;element

相關文章
相關標籤/搜索