Two Sum V2

class Solution:
    def twoSum(self, nums, target):
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        nums_length = len (nums) 
        index_1 = int ()
        index_2 = int ()
        target_list = []
        for x in range (nums_length):
            second_num = target - nums[x]
            if second_num != nums[x]:
                if second_num in nums:
                    index_2 = nums.index(second_num)
                    index_1 = x
            elif second_num in nums[x+1::]:
                index_2 = nums[x+1::].index(second_num)+x +1
                index_1 = x
        target_list = [index_1, index_2]
        return target_list

The concept in this solution:
1. have the first number,
2. second_number = target – first_number
3. check whether the second_number in list.
4. if not, then move to next number in the list
5. if yes, check whether the first number and the second number is the same: if it is the same, then make sure it is two different numbers , but starting a new list nums[x+1 ::], and then find the index in the new list. The important thing here is: for the new list starting index is not “0”, it should be “x+1”!!
6. if the second number is not the first number ,then it is easy to just identify the index.

Lesson learned:

1. how to use the value to identify the index: list_name.index(the_value)
2. the second list starting index for nums[x+1::] is x+1 , for example nums[x+1::] [y], then the original index is (x+1) +y

  1. Leave a comment

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

%d bloggers like this: