leetcode--Two Sum

来源:互联网 发布:电视机顶盒网络设置 编辑:程序博客网 时间:2024/06/04 08:29

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


题意:给你一个数组和一个target,在数组中找出两个和为target的整数。

返回这两个整数的index,并且要求index1小于index2

注意,index是基于1开始的,也就是说数组的第一个index是1,而不是0

分类:数组,Hash


解法1:由于数组是无序的,容易想到的方法就是排序以后,从头尾开始找。

排序以后,我们要记录原来元素在数组中的位置,所以创建了一个类用于记录。

在java里面我们要实现自己的比较器就可以了。排序算法的时间复杂度是O(nlogn)。

排序以后从头尾开始找,如果头尾和比target大,说明尾要减小。如果比target小,说明头要增大。

直到找到为止,时间复杂度是O(n)

所以总的时间复杂度是O(nlogn)

public class Solution {    public int[] twoSum(int[] nums, int target) {class Num{int pos;int val;public Num(int pos, int val) {this.pos = pos;this.val = val;}@Overridepublic String toString() {return val+"";}};List<Num> arr = new ArrayList<Num>();for(int i=0;i<nums.length;i++){arr.add(new Num(i,nums[i]));}Collections.sort(arr,new Comparator<Num>() {//先排序@Overridepublic int compare(Num o1, Num o2) {return o1.val>o2.val?1:-1;}});ArrayList<Integer> result = new ArrayList<Integer>();int i=0,j=nums.length-1;while(i<j){//从前后两个方向if(arr.get(i).val+arr.get(j).val>target){j--;}else if(arr.get(i).val+arr.get(j).val<target){i++;}else{result.add(arr.get(i).pos);result.add(arr.get(j).pos);i++;j--;}}Collections.sort(result);int[] r = new int[result.size()];for(i=0;i<r.length;i++){r[i] = result.get(i)+1;}return r;    }}

解法二:使用HashMap来记录元素所在的位置。

遍历数组,对于当前元素cur,用target减去cur,然后判断这个差值在hashMap中能不能找到。

如果找不到,先将cur和其index存入map

接着判断下一个元素。

public class Solution {    public int[] twoSum(int[] nums, int target) {//存储值-》位置HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();//结果,题目只要求有一组解int[] result = new int[2];for(int i=0;i<nums.length;i++){if(map.get(target-nums[i])==null){//如果差值不存在,就先存入map.put(nums[i], i);}else{//如果差值存在,得出结果result[0] = map.get(target-nums[i])+1;result[1] = i+1;break;}}return result;    }}



0 0
原创粉丝点击