Algorithm of a small daily sum of two numbers
Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.
Example:
Given nums = [2, 7, 11, 15], target = 9
Because nums [0] + nums [1] = 2 + 7 = 9
Is returned [0, 1].
The subject is not very simple ah.
This article comes from Kaige Java (kaigejava)
First of all, we think the first option is the for loop. Nested loop. as follows:
JAVA code:
public static void main(String[] args) { Integer [] nums = new Integer []{1,2,0,5,7,9,3}; Integer target = 5; Integer[] returnNums = twoSum(nums,target); System.out.println(JSON.toJSONString(returnNums)); } public static Integer[] twoSum(Integer[] nums, Integer target) { Integer[] returnNums = new Integer[2]; for (int i = 0; i < nums.length; i++) { for (int j = i+1; j < nums.length; j++) { int num1 = nums[i]; int num2 = nums[j]; if ((num1 + num2) == target) { returnNums[0] = i; returnNums[1] = j; return returnNums; } } } return returnNums; }
operation result:
The results are out. We look at execution time:
It is a way of not very low.
So then, we look at the second algorithm:
The second algorithm and clever. Java code is as follows:
private Integer[] twoSum2(Integer[] nums, Integer target) { Integer[] indexs = new Integer[2]; // 建立k-v ,一一对应的哈希表 HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for(int i = 0; i < nums.length; i++){ if(hash.containsKey(nums[i])){ indexs[0] = i; indexs[1] = hash.get(nums[i]); log.info(JSON.toJSONString(hash)); return indexs; } // 将数据存入 key为补数 ,value为下标 hash.put(target-nums[i],i); log.info("==>:{},i=:{},target-nums[i]:{}",nums[i],i,target-nums[i]); } return indexs; }
Which cleverly place:
Let's look at the results:
Look at the comparison of the two algorithms:
On another speed is not much faster.
Welcome to leave a better algorithm. Learn together, grow together