two sum

1. two sum


题目的原意是给定一个数组和目标数值,要求写出一个类的方法用来找到这个数组中的任意两个数的和等于给定目标数值。

Given: an array of integers, 

to do: find two numbers such that they add up to a specific target number.

requirement: The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2


可以提的问题:

1. 是否数组sorted?

      没有要求。

2. 找到的数有什么要求?

      需要返回的俩个数的指数,从小到大。

解题思路:考虑暴力式算法,先用一个遍历从index=0到数组末端找到一个数,再用第二个遍历从第一个遍历的index+1来找到第二个数,判断一下两个数的和是等于给定的目标数值,如果相等返回找到数值的两个index。这样的方法需要用到两次遍历所以runtime O(n^2) ,space是O(1)(只需要用到存储输出index 数组)。

要减少runtime,可以考虑使用Collections 的ArrayList 或者HashMap 来做一个中间存储器。因为ArrayList和HashMap存储的数值有index标记(Array List)或者映射到相应的已知数组的index中。当找到两个数的和等于给定的数值是返回对应数值的index即可。这种方法runtime O(n), space O(n).

小技巧:遍历的时候用 (目标值 - 当前的遍历数组中的数值)来查找已经存储在HashMap中的数值。

方法1:bruce force

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
              for (int j = 0; j < nums.length; j++) {
                  int sum = nums[i] + nums[j];
                  if (sum == target && i < j) {
                        System.out.println("Output: index1=" + (i+1) + ", index2=" + (j+1));
                   }
              }
        }
         return null;
    }
}


方法2: using mapping

public class Solution{
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
             if (map.containsKey(target-nums[i])) {
                  return new int[] {map.get(target-nums[i])+1, i+1};
             }
             map.put(nums[i], i);
         }
         throw new IllegalArgumentException("No two sum solution");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值