Leetcode——1. Two Sum
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].
方案1:时间复杂度(O(n^2))
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i = 0; i < nums.length; i++) {
for(int j = i+1; j < nums.length; j++) {
if(nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}
优化版本:时间复杂度(O(n))
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
Integer index=map.get(target-nums[i]);
if(index==null){
map.put(nums[i],i);
}else{
return new int[]{i,index};
}
}
return new int[]{0,0};
}
}
所有发生在我们身上的事件都是一个经过仔细包装的礼物。只要我们愿意面对它有时候有点丑恶的包装,带着耐心和勇气一点一点的拆开包装的话,我们会惊喜的看到里面珍藏的礼物。
----遇见未知的自己