two sum V3

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic_value_index = {}
        index_1 = int ()
        index_2 = int ()
        for index, value in enumerate(nums):
            dic_value_index [value] = index
        for item in nums:
            sec_num = target - item
            if sec_num in dic_value_index:
                if nums.index(item) != dic_value_index[sec_num]: # if they are not the same number
                    index_1 = nums.index(item)
                    index_2 = dic_value_index[sec_num]
                    break
        return ([index_1, index_2])

Key of this solution:
1. enumerate (list_name) will walk through the index and the value;
2. put the value and index into the dictinary
3. search whether the sec_num in the dictionary (only key can be searched? )
4. if yes, the the value is the index of the sec_num
5. check whether the sec_num is actually the first number, if not , then return the index.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: