two sum

来源:互联网 发布:js li默认选中样式 编辑:程序博客网 时间:2024/06/13 11:48

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].

解决方案:O(n log n)。 将索引和元素包装在一个类中,并以升序排序。 做两个index的和并比较。
一个替代的解决方案是使用一个O(n)解决方案的散列 - 对于每个元素e检查元素(target-e)
已经在hashset中找到,如果是,则返回其索引,否则将其添加到哈希集并继续。

public class TwoSum {    class NumIndex    {        int i, e;        NumIndex(int i, int e){            this.i = i;            this.e = e;        }    }    public static void main(String[] args) {        int[] nums = {3, 2, 4};        int[] ans = new TwoSum().twoSum(nums, 6);        for (int i : ans)            System.out.println(i);    }    public int[] twoSum(int[] nums, int target) {        List<NumIndex> list = new ArrayList<>();        for(int i = 0; i < nums.length; i ++){            NumIndex n = new NumIndex(i, nums[i]);            list.add(n);        }        list.sort((o1, o2) -> Integer.compare(o1.e, o2.e));        int[] ans = new int[2];        for(int i = 0, j = nums.length - 1; i < j; ){            NumIndex numi  = list.get(i);            NumIndex numj  = list.get(j);            int sum = numi.e + numj.e;            if(sum == target){                ans[0] = numi.i;                ans[1] = numj.i;                return ans;            }            else if(sum > target){                j --;            }            else i++;        }        return ans;    }}

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

public class TwoSumII{    public static void main(String[] args) throws Exception    {        int[] nums = {2, 7, 11, 15};        int[] result = new TwoSumII().twoSum(nums, 23);        for (int i : result)            System.out.println(i);    }    public int[] twoSum(int[] numbers, int target)    {        int i = 0, j = numbers.length - 1;        while(i < j)        {            int x = (numbers[i] + numbers[j]);            if(x == target)            {                int[] result = new int[2];                result[0] = i + 1;                result[1] = j + 1;                return result;            }            else if(x < target)                i++;            else j--;        }        return new int[2];    }}
原创粉丝点击