Java [leetcode 1] Two Sum, leetcodesum
I am so glad that I have finally activated my blog. I have been reading Java recently, so I have taken leetcode as a trainer. In the future, I will write down my ideas during the disintegration process and share them with you. I have my own original parts, and I also want to refer to other people's code to add my own understanding parts. I hope you will read more comments, one fuel.
Problem description:
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
Disintegration ideas:
Set up a HashMap. The key of the key is the value in the array, and the corresponding value is the value below the array.
Traverse from the beginning of the array and find whether the value corresponding to target-numbers [I] exists in HashMap each time. If the value already exists, find the sum of the two values and return the result. If the value does not exist, put (numbers [I], I) into HashMap.
The time complexity of the entire algorithm is O (n ).
The Code is as follows:
1 public class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 Map<Integer, Integer> map = new HashMap<Integer, Integer>(numbers.length * 2); 4 int[] results = new int[2]; 5 6 for(int i = 0; i < numbers.length; i++){ 7 Integer temp1 = map.get(target - numbers[i]); 8 if(temp1 == null){ 9 map.put(numbers[i], i);10 }11 else{12 results[0] = i + 1;13 results[1] = temp1 + 1;14 if(results[0] > results[1]){15 int temp2 = results[0];16 results[0] = results[1];17 results[1] = temp2;18 }19 return results;20 }21 } 22 return null; 23 }24 }