"Leetcode" 1. The problem solving report of the Sum

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/crazy1235/article/details/51471280

Subject

Source: https://leetcode.com/problems/two-sum/

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.

Example:

Given nums = [2, 7, one, +], target = 9,

Because Nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Explain

This topic is given an array of int and a target value. The sum of the numbers corresponding to the two subscripts in the array is required to be equal to target.

Returns an array of two subscript elements.

Solutionsolution 1

The stupidest way to do this is to loop the nesting.

 Public Static int[]Twosum(int[] Nums,intTarget) {int[] result =New int[2];if(Nums = =NULL|| Nums.length = =0) {returnResult } for(inti =0; i < nums.length; i++) { for(intj = i +1; J < Nums.length; J + +) {if(Nums[i] + nums[j] = = target) {result[0] = i; result[1] = J;returnResult }            }        }returnResult }

The method has a high time complexity, O (N2).
The spatial complexity is O (1).

Solution 2

Although method one passed the test, but the time complexity is high.
Then see the topic of the prompt tag is "Array" "Hash Table", it is thought to use HashMap to store subscript and value.

/** * Use HashMap storage <br/> * * @param nums * @param target * @return  * *     Public Static int[]twoSum2(int[] Nums,intTarget) {int[] result =New int[2]; Hashmap<integer, integer> map =NewHashmap<> (); for(inti =0; i < nums.length; i++) {if(Map.containskey (Target-nums[i])) {if(I > Map.get (target-nums[i])) {result[0] = Map.get (Target-nums[i]); result[1] = i; }Else{result[0] = i; result[1] = Map.get (Target-nums[i]); }            }Else{Map.put (nums[i], i); }        }returnResult }

Note Nums[i] as key, subscript I as value.
Determine if the map contains Target-nums[i] this key.

bingo~~

"Leetcode" 1. The problem solving report of the Sum

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.