Currently, I am on a speed trip after Solving LeetCode problem Two Sum .
My solution returned a 3ms .
public int[] twoSum(int[] nums, int target) {
// define return array
int[] result = {-1, -1};
// define value, index
Map<Integer, Integer> hashmap = new HashMap<>();
// define begining ptr
int lookingFor;
// for loop
for(int begPtr=0; begPtr<nums.length; begPtr++){
// does the hashmap contain this integer
lookingFor = target - nums[begPtr];
// check to see if element already exist
if(hashmap.containsKey(lookingFor)){
result[0] = begPtr;
result[1] = hashmap.get(lookingFor);
return result;
}
// add to hashmap
hashmap.put(nums[begPtr], begPtr);
}
// return
return result;
}
Here is the 1ms approach (only difference is the break in if statement ):
public int[] twoSum(int[] nums, int target) {
int[] result = {-1, -1};
Map<Integer, Integer> elements = new HashMap<>(); //number, index
for(int i = 0; i < nums.length; i++) {
int element = nums[i];
int complement = target-element;
if (elements.containsKey(complement)) {
result[0] = i;
result[1] = elements.get(complement);
break;
}
elements.put(element, i);
}
return result;
}
Why is it faster to break out of a loop and then return after the loop?
In general, you should not worry about using return
or break
. This is definitely not a point of LeetCode
task. You have a problem in another aspect of your solution.
To answer the question of why one solution is 1ms
faster, you should know the test instance setting of LeetCode
engine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.