LeetCode [1]. Two Sum -- different java methods, leetcodesum -- java

Source: Internet
Author: User

LeetCode [1]. Two Sum -- different java methods, leetcodesum -- java

LeetCode


I was so ashamed to know that such a good platform could be used to answer questions recently. Now, let's make a try! At the beginning, there are inevitably some shortcomings and some part that borrow others' ideas to learn and make progress!

Start to do the first question Two Sum as follows:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum shocould return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers = {2, 7, 11, 15}, target = 9
Output: index1 = 1, index2 = 2

Simply put, an array and a value are given, and the two elements in the array are added as the index of the value. Index1 light rain index2 is required, and the answer is stable.

Ideas:

1. traversal:The most crude method. The time complexity is O (n ^ 2 ). It was too time-consuming to submit traffic at the beginning. Slightly Strange.

public class Solution {    public int[] twoSum(int[] nums, int target) {        int index1,index2;        int[] index=new int[]{0,1};        for(int i = 0; i< nums.length; i++)        {            for(int j = i+1; j< nums.length; j++)            {                if(target==(nums[i]+nums[j]))                {                    index[0] = i+1;                    index[1] = j+1;                    return index;                }            }        }        return index;    }   }

Ii. HashSet:Use the principle that the HashSet element cannot be repeated to create a new HashSet, and then check whether target-nums [I] can be added to the HashSet. If yes, it indicates that the preceding data does not have a combination that matches the I. Delete the target-nums [I] and re-add nums [I] (to avoid returning an error judgment if two elements are equal ). If the addition is unsuccessful, it indicates that a matched combination exists. Record the I at this time and search for the other half from the array before I. It is a little tedious, but the time complexity is O (n), and the space complexity is O (n ).


Public class Solution {public int [] twoSum (int [] nums, int target) {int index1, index2; int [] index = new int [] {0, 1 }; set nset = new HashSet (); for (int I = 0; I <nums. length; I ++) {if (nset. add (target-nums [I]) // check whether a nums [I] pair element exists. If not, the addition is successful {nset. remove (target-nums [I]); // This element is added only to determine whether it exists. nset should not be added here. add (nums [I]);} else {index [1] = I + 1; for (int j = 0; j <I; j ++) {if (target = (nums [I] + nums [j]) {index [0] = j + 1; return index ;}} return index ;}}
It is a bit strange that the above submitted result is "Runtime: 332 ms", but I replaced the method of using the add () method to determine whether it exists with the method of using contains () directly () if (nset. change "add (target-nums [I])" to "if (! Nset. contains (target-nums [I]) "and then delete" nset. remove (target-nums [I]); ", but" Runtime: 364 ms ". I tried it several times and the size changed, but the latter always takes more time. However, one less command is actually executed. I am a bit confused here. I do not know whether the black box test is used to verify the correctness of the algorithm.

In addition, some people may wonder if the HashSet judges whether an existing element does not need to traverse an existing set when adding elements? Isn't this the same as traversing the first method? In fact, the location where HashSet elements are stored depends on the hash code of each element, that is, the address where an element is stored by knowing its hash code and calculating its hash code. Like a school, every time a freshman comes, he will receive a student ID. The teacher will ask you not to go to a dormitory to find you. As long as you know the student ID, you will be able to directly locate your dormitory.


Iii. HashMap:HashMap is the same, but it is a little different from binary. 1. HashMap needs to create two Memory Spaces for each element: key and value, doubling the auxiliary space. In this example, we use value to place the index. 2. Because value is used to place the index, after finding one, the other will immediately get its index. There is no big difference between two and three, one saving point space and one saving point time.

public class Solution {      public int[] twoSum(int[] nums, int target) {          int[] index=new int[]{0,1};        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();                for(int i = 0; i<nums.length; i++)        {            if(hm.containsKey(target - nums[i]))            {                index[1] = i+1;                index[0] = hm.get(target-nums[i])+1;                   return index;               }else            {                 hm.put(nums[i],i);            }        }        return index;      }     }  



Reference: LeetCode-Two Sum (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.