[Leetcode] 001. Both Sum (Medium) (C++/java/python)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

001.two_sum (Medium) links

Title: https://oj.leetcode.com/problems/two-sum/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

The number of the two positions in an array is the same as the target, seeking both positions.

Analysis

The violence of finding the past complexity is O (n^2), will TLE.

    1. You can sort and then use the double pointer to the middle clamp force, the complexity O (NLOGN).
    2. You can use the map to record the number of occurrences, as long as the current number to determine whether the number of target, and then find out the line, the complexity O (nlogn) rather than O (n), because the MAP is also complex.
    3. The Map complexity in 2 can be made up of arrays, with the time complexity O (n), but the spatial complexity is O (MAXN).
Code

Method one: Double pointers

classSolution { Public: vector<int>Twosum ( vector<int>&numbers,intTarget) {intSZ = Numbers.size ();intleft =0, right = SZ-1, sum =0; vector<int>Sorted (numbers);STD:: Sort (Sorted.begin (), Sorted.end ()); vector<int>Index while(Left < right) {sum = Sorted[left] + sorted[right];if(sum = = target) {//Find the answer                     for(inti =0; I < sz; i++) {if(Numbers[i] = = Sorted[left]) index.push_back (i +1);Else if(Numbers[i] = = Sorted[right]) index.push_back (i +1);if(index.size () = =2)returnIndex }                }Else if(Sum > Target)                {right--; }Else{left++; }            }//Program never go here, because            //"Each input would has exactly one solution"}};

Java:

 Public  class solution {    StaticClass Pair implements Comparable<pair> {intvalue, index; Public Pair(intVintID) {value = V;        index = ID; }@Override         Public int CompareTo(Pair b) {return  This. Value-b.value; }    } Public Static int[]Twosum(int[] numbers,intTarget) {int[] res =New int[2]; Pair[] Pairs =NewPair[numbers.length];//Get pairs and sort         for(inti =0; i < numbers.length; ++i) {Pairs[i] =NewPair (Numbers[i], i +1); } arrays.sort (pairs);//Points        intleft =0, right = Numbers.length-1, sum =0; while(Left < right) {sum = Pairs[left].value + pairs[right].value;if(sum = = target) {res[0] = Pairs[left].index; res[1] = Pairs[right].index;if(res[0] > res[1]) {//swap themres[0] ^= res[1]; res[1] ^= res[0]; res[0] ^= res[1]; } Break; }Else if(Sum > Target)            {--right; }Else{++left; }        }returnRes }}

Python:

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

Method Two: Map

C++:

Const intN =200002;Const intOFFSET =100000;classSolution {Private:intIdofnum[n]; Public: vector<int>Twosum ( vector<int>&numbers,intTarget) { vector<int>Indexmemset(Idofnum,0,sizeof(Idofnum));intSZ = Numbers.size (); for(inti =0; I < sz; i++) {intRest = Target-numbers[i];if(Idofnum[rest + OFFSET])                    {Index.push_back (idofnum[rest + OFFSET]); Index.push_back (i +1);returnIndex } Idofnum[numbers[i] + OFFSET] = i +1; }//Program never go here, because            //"Each input would has exactly one solution"}};

Java:

 Public  class solution {     Public Static int[]Twosum(int[] numbers,intTarget) {int[] res =New int[2]; Hashmap<integer, integer> nums =NewHashmap<integer, integer> (); for(inti =0; i < numbers.length; ++i) {//Add i-th numberInteger a = Nums.get (Numbers[i]);if(A = =NULL) Nums.put (Numbers[i], i);//Find (Target-numbers[i])A = Nums.get (Target-numbers[i]);if(A! =NULL&& a < i) {res[0] = a +1; res[1] = i +1; Break; }        }returnRes }}

Python:

class Solution:    # @return a tuple, (index1, index2)    def twoSum(self, num, target):        dictMap = {}        forin enumerate(num):            ifin dictMap:                return11            dictMap[value] = index

Method Three: Array

C + +: (In contrast to method two)

Const intN =200002;Const intOFFSET =100000;classSolution {Private:intIdofnum[n]; Public: vector<int>Twosum ( vector<int>&numbers,intTarget) { vector<int>Indexmemset(Idofnum,0,sizeof(Idofnum));intSZ = Numbers.size (); for(inti =0; I < sz; i++) {intRest = Target-numbers[i];if(Idofnum[rest + OFFSET])                    {Index.push_back (idofnum[rest + OFFSET]); Index.push_back (i +1);returnIndex } Idofnum[numbers[i] + OFFSET] = i +1; }//Program never go here, because            //"Each input would has exactly one solution"}};

[Leetcode] 001. Both Sum (Medium) (C++/java/python)

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.