And programmers code farmers know the difference lies in data structures and algorithms, so I began to brush Leetcode topic of road, hee hee
topic
Given an array of integers, returns two numbers index , so that they are applied to specific targets.
You can assume that each input is only one solution, and you may not be twice using the same elements.
Given nums = [2,7,11,15], target = 9, since the nums [ 0 ] + the nums [ 1 ] = 2. 7 = +. 9, returns to [ 0 , 1 ].
A Solution
thought
Brute force, twice the number of loops through the array is equal to the sum of each target, and then returns the index
class Solution { public int[] twoSum(int[] nums, int target) { int[] arrs=new int[2]; ; int sum=0; for (int i = 0; i <nums.length; i++) { for (int j = 0; j <nums.length&&i!=j ; j++) { sum=nums[i]+nums[j]; if(target==sum){ arrs[0]=i; arrs[1]=j; } } } return arrs; } }
result
When execution: 95 MS , beat the 8.21% of all users to submit in Java
Memory consumption: 37.2 MB , defeated 90.74% of all users to submit in Java
When used too long, the typical time for space approach
Solution two
Thinking
int[] arrs=new int[2]; ; int sum=0; HashMap<Integer,Integer> hashMap=new HashMap<>(); for (int i = 0; i <nums.length; i++) { hashMap.put(nums[i],i); } for (int i = 0; i <nums.length; i++) { int num=target-nums[i]; if(hashMap.containsKey(num)&&hashMap.get(num)!=i){ arrs[0]=i; arrs[1]=hashMap.get(num); break; } } return arrs;
result
When execution: 7 ms, beat the 88.43% of all users to submit in Java
Memory consumption: 38.9 MB, defeated 51.18% of all users to submit in Java