Leetcode 1, leetcode

Source: Internet
Author: User

Leetcode 1, leetcode
Question

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

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Solution
Public int [] TwoSum (int [] nums, int target) {# region solution 1, brute force cracking method int [] newInt = null; for (int I = 0; I <nums. length; I ++) {for (int j = I + 1; j <nums. length; j ++) {if (nums [I] + nums [j] = target) {newInt = new int [] {I, j };}}} return newInt; # endregion # region solution 2, dictionary <key, value> int [] arr = new int [2]; Dictionary <int, int> dict = new Dictionary <int, int> (); for (int I = 0; I <nums. length; I ++) {int cha = target-nums [I]; if (dict. containsKey (cha) {arr [0] = dict [cha]; arr [1] = I; break;} else {dict. add (nums [I], I) ;}return arr; # endregion}

Solution on OJ: https://leetcode.com/articles/two-sum/

The first leetcode is HashTable. in C #, It is Dictionary <key, value>.

Related Article

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.