首页 > 其他 > 详细

Two Sum

时间:2014-07-23 22:20:57      阅读:458      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
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;
       
    }
}

Two Sum,布布扣,bubuko.com

Two Sum

原文:http://www.cnblogs.com/hansongjiang/p/3864087.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!