您的位置:首页 > 编程语言 > Java开发

leetcode - 1. Two Sum (java)

2018-01-25 19:19 405 查看
Problem:

 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]


解释:给定一个整型数据的数组,找到两个数,加起来等于所给的target的值。返回这两个数在数组中的下标。

(假定都有答案且每个数字只能用一次)

Solve:
 1.简单暴力,直接两重循环查找,找到这两个数字就返回结果(时间复杂度O(n^2),AC-39ms)

public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i <nums.length ; i++) {
for (int j = i+1; j <nums.length ; j++) {
if(nums[i]+nums[j]==target){
int []re={i,j};
return re;
}
}
}
return null;
}

  2.调用JAVA中的map来保存查找数字。将查找交给map降低复杂度,(时间复杂度O(n),AC-9ms)

public static int[] twoSum1(int[] nums,int target){
HashMap<Integer,Integer> map=new HashMap();
for (int i = 0; i <nums.length ; i++) {//保存至map。
map.put(nums[i],i);
}
for (int i = 0; i <nums.length ; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {//查找map
return new int[] { i, map.get(complement)};
}
}
return null;
}

后记:emmm,很久前就想写点博客记录下,刚好放寒假,科目二挂科 mmp,顺手来写了,代码之前写的,尽量保持一天写一题吧。兴趣使然,想写就写。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode