1. Two Sum

来源:互联网 发布:淘宝上显示喵喵折 编辑:程序博客网 时间:2024/05/29 09:54

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

Solution1 HashMap

6ms 58.80%

public class Solution {    public int[] twoSum(int[] nums, int target) {       int res [] = new int [2];       Map<Integer, Integer> map = new HashMap<Integer, Integer>();       for(int i = 0; i < nums.length; i++){           if(!map.containsKey(target - nums[i])){               map.put(nums[i], i + 1);           }else{               res[0] = map.get(target - nums[i]);               res[1] = i + 1;               return res;           }       }       return res;    }}

Solution 2 Use another array to keep the index of elements in the current array, and sort the array, use two pointers to find the elements.

(findIndex() pre is used to prevent get the same element in the array)

5mw 90.26

public class Solution {    public int[] twoSum(int[] nums, int target) {       int[] temp = new int[2];        int[] nums_sort = nums.clone();        Arrays.sort(nums_sort);        int start = 0;        int end = nums_sort.length - 1;        while(start < end){            if((nums_sort[start] + nums_sort[end]) == target){                temp[0] = getIndex(nums_sort[start], nums);                temp[1] = getIndex(nums_sort[end], nums);                if(temp[0] > temp[1]){                    int a = temp[1];                    temp[1] = temp[0];                    temp[0] = a;                }                break;            }            else if((nums_sort[start] + nums_sort[end]) < target){                start += 1;            }            else if((nums_sort[start] + nums_sort[end]) > target){                end -= 1;            }        }        if(start >= end){            temp = null;        }        return temp;    }     public int getIndex(int temp, int[] nums){        for(int i=0;i<nums.length;i++){            if(temp == nums[i])            return i+1;        }        return 0;    }}


0 0
原创粉丝点击