Leetcode oj_ (Python): 001-two Sum "Array" "Easy"

Source: Internet
Author: User

Topic:

Given an array of integers, return indices of the both numbers such that they add-to a specific target.

You may assume this each input would has exactly one solution, and you could not use the same element Twi Ce.

Enter an array and target to find two numbers in an array, and a position of two digits for target, from small to large output array. The topic assumes that there is only one answer.

Example:

Given nums = [2, 7, one, 2], target = 9,because nums[0] + nums[1] = + 7 = 9,return [0, 1].
Topic Ideas:

① If the direct violence is resolved, the time complexity is (O (n^2)), two loops, respectively, from the array to find two num, the sum of which equals target.

② so if the given array is ordered, will it reduce the difficulty? If it is an ordered array, then we can use the "pinch theorem" to deal with. In simple terms, if the end is larger than the target, then move the mantissa to the left, if it is smaller and right, until the two number is exactly equal to target, then we can sort the array first and then use the double pointer to the middle "clamp force", the time complexity of this method is (O (NLOGN). The way to note this is to sort the original position of the array and then sort it.

③ There is also a way to use a dictionary. In Python there is a dictionary and C + + map function. First, we set up a dictionary, d = {}, the dictionary key is the value of the array num,value is the corresponding position, and then as long as the number of NUM and target-num in the dictionary find the answer. At the beginning, the dictionary is empty, starting from the list to read the values, and when Num and target-num are found, stop looking. The time complexity of this method is (O (n)), but the spatial complexity is O (MAXN).

Code:

Ii

classSolution:#@return A tuple, (index1, Index2)    deftwosum (self, num, target):#SortSorted_num =sorted (num)#pointsleft =0 Right= Len (num)-1Res= []         while(Left <Right ): Sum= Sorted_num[left] +Sorted_num[right]ifsum = =Target:#Find out Index                 Break; elifSum >Target:right-= 1Else: Left+ = 1ifleft = =Right :return-1,-1Else: Pos1= Num.index (Sorted_num[left]) + 1Pos2= Num.index (Sorted_num[right]) + 1ifPOS1 = = Pos2:#Find againPos2 = Num[pos1:].index (Sorted_num[right]) + POS1 + 1returnMin (pos1, Pos2), Max (POS1, Pos2)

classsolution (object):deftwosum (self, Nums, target):""": Type Nums:list[int]: type Target:int:rtype:list[int]"""D= {}#D is a dictionary to map the value of Nums and the index in NumsSize =0 whileSize <Len (nums):if  notNums[size]inchD:d[nums[size]]= size + 1#if nums[size] doesn ' t exist in D, create it            ifTarget-nums[size]inchD:#if nums[size] and Target-nums[size] is both in D                ifD[target-nums[size]] < size + 1:#One situation should be minded nums[size] = = Target-nums[size]Ans = [d[target-nums[size]], size + 1]#For example [0,1,2] 0 and [0,1,2,0],0                    returnans size= size + 1

Ps:

If you want to use Pycharm for debugging, you can use the main function (put it at the end of the program):

if __name__ " __main__ " :     = solution ()    print(S.twosum ([4, 2, 3, 6], 8))

Results:

Leetcode oj_ (Python): 001-two Sum "Array" "Easy"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.