1. Two Sum

来源:互联网 发布:网贷安卓源码 编辑:程序博客网 时间:2024/06/15 16:11

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 thesame element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
第一次提交:failed 代码如下:
class Solution {    public int[] twoSum(int[] nums, int target) {  for(int i=0; i < nums.length; i++){         int rest = target - nums[i];            int find = Arrays.binarySearch(nums,rest);            System.out.println("first:"+find);            if(find>=0){             if(find==i){              nums[find] = -1;              this.out(nums);              find = Arrays.binarySearch(nums,rest);              System.out.println("rest:"+rest);              System.out.println("find:"+find);              if(find<0)               continue;              }             System.out.println("ds");                result[0]=i;                result[1]=find;                return result;            }        }        return result;    }
问题:如果有相同数字出现有问题。例如当nums=[3,3],target=6时。第二次提交:
public int[] twoSum(int[] nums, int target) {        int[] result = new int[2];        List<Integer> temp = new ArrayList<Integer>();        for (int i = 0;i<nums.length;i++){        temp.add(nums[i]);        }        for(int i=0;i<temp.size();i++){        int rest  = target-temp.get(i);        if(rest==temp.get(i))        temp.set(i, -1);        int find = temp.indexOf(rest);        if(find!=-1){        result[0] = i;        result[1] = find;        return result;        }        }        return result;
增加了判断,如果target和target-nums[i]相同就找该数字第二次出现的下标。
但是这种搜索效率不高(why?)
参考比较快的方法:利用hash map:
class Solution {    public int[] twoSum(int[] nums, int target) {        HashMap<Integer,Integer> map = new HashMap<>();        for (int i = 0;i<nums.length;i++){        if(map.get(nums[i])!=null){                int[] result = {map.get(nums[i]),i};                return result;            }            map.put(target-nums[i],i);        }        int[] result = {};        return result;    }}
从前往后把target-nums[i]和编号i进行hash,再判断后面的里面是否存在这个数。这样就不用担心数字相同时候先后出现问题。
时间复杂度这一块还不懂~~