码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum

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

标签:style   blog   http   color   os   io   

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

标签:style   blog   http   color   os   io   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!