leetcode-001

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目给出的限制条件是:每个输入的数组都恰好只有唯一一个解。

有两种解决方法:

1 朴素解法:index1指向数组第一个元素,然后用index2从数组第一个元素开始,遍历数组,知道找到nums[index1] + nums[index2] = target。如果找不到index2,则index++;然后index2 =0;继续遍历数组,直到index1=  nums.length,退出。

这种解法时间复杂度是O(n^2);太慢

2使用HashMap<Integer ,Integer>。将HashMap的key设定为target-nums[i],value设定为 i 。读取nums[i] ,然后只要判断target-nums[ i ]是否在HashMap中即可,若在,则返回 i  和 map.get(target - nums[ i]);

 public int[] twoSum(int[] nums, int target){

         int len = nums.length;
         int[] result = new int[2];

         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
         for(int i=0;i<n;i++){
              if(map.containsKey(nums[i])){
                  result[0] = map.get(nums[i]); //得到nums[i] 对应的在nums中的index
                  result[1] = i;//target-nums[i]对应的index2
                  break;
              }
              else{
                 map.put(target - nums[i], i);//map中key是target-nums[i],value是 i 
              }
        }

      return result;
}
思考:

如果数组中有多个值满足nums[i] + nums[j] = target,那么result[ ]该设置为多大长度?

若设置为nums.length,则result[ ]中未使用的部分值都为0,返回的result不正确。在新建一个数组,长度为result中去掉后面的0之后的长度,将result中的值copy到新数组 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值