Path to my LC-1. Two Sum, lcsum

Source: Internet
Author: User

Path to my LC-1. Two Sum, lcsum

Preface: for the questions made on LeetCode, the code is basically written by myself, and the efficiency is good or bad, which is for reference only.
There are a few questions that cannot be solved by thinking and meditation. They may learn from the solutions of the online experts, and then write them on their own. The questions that have been solved by others will be explained.
I am not an algorithm, and the language is basically self-taught. If you have any misunderstanding or improper actions, please kindly advise me! Thank you very much ~

In order to prevent audience members from switching back and forth, I have to post the question by the way (in fact, I am too lazy to reply back and forth ~ Haha ):

1. Two Sum

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

You may assume that each input wocould haveExactlyOne solution, and you may not useSameElement twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

Solution:

When I got this question, I immediately thought of traversing the two groups of times, adding them one by one, and comparing them with the target. Although this method is relatively simple and crude, the efficiency is definitely quite the same.

My principle is generally:Focuses on solving problems.

Therefore, no matter how complicated it is, you can do it first.

The Code is as follows:

 1 public class Solution { 2     public int[] twoSum(int[] nums, int target) { 3         int[] res = null; 4         for(int i=0;i<nums.length;i++){ 5             for(int j=nums.length-1;j>=0;j--){ 6                 if(nums[i]+nums[j]==target&&i!=j){ 7                     res = new int[2]; 8                     res[0] = i; 9                     res[1] = j;10                 }11             }12         }13         return res;14     }15 }

I submitted it once. It seems that LeetCode's first question is not intended to combat everyone's enthusiasm ~ Haha

The question is done, but it is still stupid, so I am ready to think about how to optimize the performance.

If you want to go, I feel that my level is limited and there are not many improvements...

The containsKey method in hashmap can be used to quickly find out whether the values saved in hashmap contain key values. Based on this feature, you can quickly compare values.

To see the complexity, I am Zheng (zhuang) heavy (mu) His (zuo) incident (yang) looked at the containsKey method in HashMap and found the source code, it is found that there is only one simple sentence:

1     public boolean containsKey(Object key) {2         return getNode(hash(key), key) != null;3     }

If you continue to find the getNode method, you will find that it is based on the hash value of the key. The source code is more complex and I have a hard time reading it. I will not go into it here!

Return to our question and use hashmap to change the method:

 1 class Solution { 2     public int[] twoSum(int[] nums, int target) { 3         int temp = 0; 4         int[] result = {0,0}; 5         Map<Integer,Integer> m = new HashMap<>(); 6         for(int i = 0;i<nums.length;i++){ 7             temp = target-nums[i]; 8             if(m.containsKey(temp)){ 9                 result[0] = m.get(temp);10                 result[1] = i;11             }12             m.put(nums[i],i);13         }14 15         return result;16 17     }18 }

After the submission, I checked the time. It took 10 ms and the above was 73 ms. It seems that the results are indeed much faster.

Here, we set the value as the key and the subscript as the value because the subscript needs to be output in the final result, which is more convenient. More importantly, the question clearly indicates the haveExactlyOne solution.

Otherwise, using the values in the array as the key cannot solve the problem. Because 1, according to the characteristics of hashmap, the key to be stored will replace the key to be saved first. If there are multiple solutions, for example: nums = [2, 7, 7, 11, 15], target = 9. In this way, only [0, 2] can be obtained, and [0, 1] cannot be obtained :)

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.