Leetcode Sum correlation algorithm problem

Source: Internet
Author: User

1. Both Sum (https://oj.leetcode.com/problems/two-sum/)

Problem Solving Ideas:

Solution One: Violence, O (N2) time complexity, TLE

Solution two: Using hash, record the subscript of each value in the array, and then iterate through the array again, by looking at whether the value of target-num[i] is in the map to determine another value. Time complexity O (n)

Solution Three: Sort the num array, O (Nlog (n)), then pinch O (n) left and right. But this problem requires record subscript, so this method is not feasible.

The Python code is as follows:

1   deftwosum (self, num, target):2D = {}3Lennum =len (num)4Ans = []5      forIinchxrange (lennum):6D[num[i]] = [I+1]ifNum[i] not inchDElseD[num[i]] + [i+1]7      forIinchNum:8res = target-I9       ifResinchD:Ten         ifres = =I: One           ifLen (d[i]) = = 2:return(D[i][0], d[i][1]) A         Else: -           return(D[i][0], d[res][0])ifD[i][0] < d[res][0]Else(D[res][0], d[i][0])

Leetcode Sum correlation algorithm problem

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.