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].
 
第一次提交: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,再判断后面的里面是否存在这个数。这样就不用担心数字相同时候先后出现问题。
时间复杂度这一块还不懂~~




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值