LeetCode解题 1:Two Sum
Problem 1: Two Sum [Easy]
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
来源:LeetCode
Solution (Java)
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
for(int i = 0; i < len; i++){
for(int j = i+1; j < len; j++){
if(nums[i] + nums[j] == target){
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No solution");
}
}
修改过程
- 第一层循环只到len/2导致没有搜索到两个索引都在数组后半部分的结果。(写的时候脑抽?)
- 改进:比起在两层循环结束后返回结果,在搜索到结果之后直接return显得更为简洁。