[LeetCode]1. Two Sum

来源:互联网 发布:windows vista系统重装 编辑:程序博客网 时间:2024/06/11 17:03

Problem Description

Given an array of integers, 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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
[https://leetcode.com/problems/two-sum/]

思路

先把每个数字的位置用hashtable保存下来,这里要注意会有相同的数字,所以我用了两个hashtable,毕竟相同的数字如果要作为答案的话,只需要前两个位置的数字即可。
然后将nums排序,方便剪枝。
之后就是两层循环就好了。
如果用DP会不会更快呢?~

Code

package Q1;import java.util.Arrays;import java.util.Hashtable;public class Solution {    public static int getMax(int[] nums) {        int max = 0;        for (int i = 0; i < nums.length; i++)            max = Math.max(max, nums[i]);        return max;    }    @SuppressWarnings({ "unchecked", "rawtypes" })    public static int[] twoSum(int[] nums, int target) {        int[] ans = { 0, 0 };        Hashtable index1 = new Hashtable();        Hashtable index2 = new Hashtable();        for (int i = 0; i < nums.length; i++) {            if (index1.containsKey(nums[i]) && !index2.containsKey(nums[i])) {                index2.put(nums[i], i + 1);            } else if (!index1.containsKey(nums[i]))                index1.put(nums[i], i + 1);        }        int tmp = 0;        Arrays.sort(nums);        for (int i = 0; i < nums.length; i++) {            for (int j = 0; j < nums.length; j++) {                tmp = nums[i] + nums[j];                if (tmp > target)                    break;                else if (tmp == target) {                    if (nums[i] == nums[j]) {                        ans[0] = Integer.parseInt(index1.get(nums[i])                                .toString());                        ans[1] = Integer.parseInt(index2.get(nums[j])                                .toString());                    } else {                        ans[0] = Integer.parseInt(index1.get(nums[i])                                .toString());                        ans[1] = Integer.parseInt(index1.get(nums[j])                                .toString());                    }                    Arrays.sort(ans);                    return ans;                }            }            if (nums[i] > target)                break;        }        return ans;    }    // public static void main(String[] args) {    // int a[]={-1,-2,-3,-4,-5};    // int t=-8;    // int[] ans=twoSum(a, t);    // System.out.print(ans[0]+" "+ans[1]);    //    // }}
0 0
原创粉丝点击