您的位置:首页 > 其它

leetcode Two Sum 解决思路

2017-07-18 18:56 453 查看
/*
* 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.
给出一个int数组,返回数组中两个数下标,这两个数相加等于一个给出的int数,每个数只能用一次,不能自己加自己
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
例如:
条件: nums = [2, 7, 11, 15], target = 9,
满足: nums[0] + nums[1] = 2 + 7 = 9,
返回 : [0, 1].
*/
public class Solution {
public static int[] twoSum1(int[] nums, int target) {
if (nums == null) {
return null;
}
// 返回值
int result[] = new int[2];
// 遍历
for (int i = 0; i < nums.length; i++) {
// 从当前下标下一位数开始遍历 不会自己加自己
for (int j = i + 1; j < nums.length; j++) {
// 如果相加等于目标 就返回当前i j
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
}
}
}
return result;
}

public static int[] twoSum2(int[] nums, int target) {
if (nums == null) {
return null;
}
// 返回值
int result[] = new int[2];
// 这个map用来存放已经遍历过的数据 (不用进行双层循环)
Map<Integer, Integer> gone = new HashMap<>();
// 遍历数字数组
for (int i = 0; i < nums.length; i++) {
// 如果已经遍历过的数中存在一个与当前数相加等于target 则返回两位数的下标
if (gone.containsKey(target - nums[i])) {
result[0] = gone.get(target - nums[i]);
result[1] = i;
}
gone.put(nums[i], i);
}
return result;
}

public static void main(String[] args) {
//测试
int ints [] ={3,2,4};
int targrt = 6;
int res[] = twoSum1(ints,targrt);
int res2[] = twoSum2(ints,targrt);

if(res != null){
for (int i = 0; i < res.length; i++) {
System.out.print("第"+(i+1)+"个下标:"+res[i]+"  ");
}
}
System.out.println();
if(res2 != null){
for (int i = 0; i < res2.length; i++) {
System.out.print("第"+(i+1)+"个下标:"+res2[i]+"  ");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: