LeetCode|Two Sum-java

来源:互联网 发布:会计软件的基本功能 编辑:程序博客网 时间:2024/06/05 03:24

题目

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

需要注意的:数组并不是排序的数组

public class Solution {    /**     * 思路一:     * 将数组拷贝出一份,对数组进行排序,然后使用head和end指针移动查      * 找答案,最后在原数组中查找相应的相应的位置。     * 空间复杂度:o(n)     * 时间复杂度:o(nlogn+n+n) = o(nlogn)     *      * */    public int[] twoSum(int[] nums, int target) {        int[] temp = Arrays.copyOfRange(nums, 0, nums.length);        Arrays.sort(temp);        int head = 0;        int end = temp.length - 1;        int sum = temp[head] + temp[end];        while (sum != target && head < end) {            sum = temp[head] + temp[end];            if (sum < target) {                head++;            } else if (sum > target) {                end--;            }        }       if (head != end) {            int[] result = {-1, -1};            for (int i = 0; i < nums.length; i++) {                if (nums[i] == temp[head] && result[0] == -1) {                    result[0] = i;                } else if (nums[i] == temp[end] && result[1] == -1) {                    result[1] = i;                } else if (result[0] != -1 && result[1] != -1) {                    break;                }            }            Arrays.sort(result);            return result;        }        return null;    }}public class Solution {    /**     * 思路二:     * 将数组的值和相应的位置信息存储到hashMap中,Key存储数组的值,Value存贮该值得位置,     * 然后遍历整个数组,因为数组中有且只有一对数字的合等于目标数字,所以将每次遍历的数字与目标数字相减,     * 查看hasMap中是否有相应的结果     * 空间复杂度:o(n)     * 时间复杂度:o(n);     *      * */     public int[] twoSum(int[] nums, int target) {        if (nums == null || nums.length == 0) return null;        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();        for (int i = 0; i < nums.length; i++) {            hashMap.put(nums[i], i);        }        int[] result = null;        for (int i = 0; i < nums.length; i++) {            int num = nums[i];            int res = target - num;            if (hashMap.containsKey(res) && hashMap.get(res) != i) {                result = new int[2];                result[0] = i;                result[1] = hashMap.get(res);                break;            }        }        return result;    }}
0 0