1. The sum of two "Leetcode China, by Java"

Source: Internet
Author: User

Given an array of integers and a target value, find the two numbers in the array and the target values.

You can assume that each input corresponds to only one answer, and that the same element cannot be reused.

Example:

Given nums = [2, 7, one, a], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1]

Problem solving: Today found Leetcode original website, do not know is not the wall, had to shift position. This topic is still relatively simple, the method is more, first look at the first, violent solution, double cycle to determine whether the two value and is equal to target. The code is as follows:

1 classSolution {2      Public int[] Twosum (int[] Nums,inttarget) {3         int[] result =New int[2];4        //Arrays.sort (nums);5          for(inti = 0; i < nums.length-1; i++){6              for(intj = i + 1; J < Nums.length; J + + ){7                 if(Nums[i] + nums[j] = =target) {8Result[0] =i;9RESULT[1] =J;Ten                     returnresult; One                 } A             } -         } -         return NULL; the     } -}

can also use a hash table to do, space change time. Put each element and its corresponding position into the HashMap, before the first to determine whether there is already a corresponding number of data in the table, with which can be the target, there is a return result, not continue to put. The code is as follows:

1 classSolution {2      Public int[] Twosum (int[] Nums,inttarget) {3Map<integer, Integer>map =NewHashmap<integer,integer>();4          for(inti = 0; i < nums.length; i++){5             if(Map.containskey (Target-Nums[i]))6                return New int[]{map.get (Target-Nums[i]), i};7 Map.put (Nums[i], i);8         }9                Throw Newillegalargumentexception ();Ten     } One}

1. The sum of two "Leetcode China, by Java"

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.