Two Sum

来源:互联网 发布:项目建议书软件 编辑:程序博客网 时间:2024/05/02 04:43
  1. 题目
    Given an array of integers, find two numbers such that they add up to a specific target number
    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
    你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。
    给出 numbers = [2, 7, 11, 15], target = 9, 返回 [1, 2].

  2. 算法
    暴力方法:两两相加,直到和为给定数为止,设总共n个数步骤如下
    1 第i个数分别与后面n-i个数相加,如果和为给定数,则返回
    2 循环步骤1,直到第n-1个数

  public int[] twoSum(int[] numbers, int target) {        // write your code here        int[] res = new int[2];        if (numbers == null && numbers.length < 2) {            return null;        }        for (int i = 0; i < numbers.length - 1; i++) {     //第i个数与后面数相加            for (int j = i + 1;  j < numbers.length; j++) {                if (numbers[i] + numbers[j] == target) {   //如果相加为target,则返回                    res[0] = i + 1;                      // 不是从0开始,下标加1                    res[1] = j + 1;                    return res;                }            }        }        return res;    }

hash表:一中优化方法是用哈希表,hashtable中查找元素时间为常数,我们用HashMap来存储数据,键存储数组值,值存储数组下标,步骤如下
1 从第一个元素开始,如果target和元素差没在HashMap中,我们把元素存进HashMap,如果在则返回,
2 重复步骤1,直到最后一个元素

    public int[] twoSum(int[] numbers, int target) {        // write your code here        int[] res = new int[2];        if (numbers == null && numbers.length < 2) {            return null;        }        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); //键存值,值存下标        for (int i = 0; i < numbers.length; i++) {               if (hm.containsKey(target - numbers[i])) {      // 符号条件,返回                res[0] = hm.get(target - numbers[i]) + 1;                res[1] = i + 1;                return res;            }            hm.put(numbers[i], i);      //不符合条件,存储元素        }        return res;    }
0 0
原创粉丝点击