首页 > 代码库 > Two Sum

Two Sum

1.hashMap方法O(n)空间换时间

public class Solution {    public int[] twoSum(int[] numbers, int target) {        HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();        int ans[]=new int[2];        for(int i=0;i<numbers.length;i++)        {            if(hash.containsKey(target-numbers[i]))            {                ans[0]=hash.get(target-numbers[i])+1;                ans[1]=i+1;                return ans;                            }            else hash.put(numbers[i],i);                    }                            return ans;    }}
View Code

2. 排序后获取两个值

class node implements Comparable<node>{    int x;    int y;    public int compareTo(node n)    {        return this.x-n.x;                    }    public node(int x,int y)    {        this.x=x;        this.y=y;            }}public class Solution {        public int[] twoSum(int[] numbers, int target) {        node n[]=new node[numbers.length];        for(int j=0;j<numbers.length;j++)        {            n[j]=new node(numbers[j],j+1);        }        Arrays.sort(n);                            int ans[]=new int[2];        int low=0;        int high=numbers.length-1;        while(low<high)        {            int sum=n[low].x+n[high].x;            if(sum==target)            {                ans[0]=n[low].y;                ans[1]=n[high].y;                if(n[low].y>n[high].y)                {                    ans[0]=n[high].y;                    ans[1]=n[low].y;                }                        break;            }            else if(sum>target) high--;            else  low++;                                                       }                return ans;           }}