Given an array A[] and a number x, check for pair in A[] with sum as x

 

http://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/

    public int[] twoSum(int[] numbers, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int[] r = {};
        if(numbers == null|| numbers.length == 0)
            return r;
        
        int n = numbers.length;
        
        r = new int[n];
        int count=0;
        int i =0,temp= 0;
        
        //set a large array.
        int[] binMap = new int[10000];
        
        for(i =0;i<n;i++)
        {
            temp = target-numbers[i];
            if(temp>=0 && (binMap[temp]==1))
            {
                r[count++]=numbers[i];
                r[count++]= temp;
            }
            binMap[numbers[i]] =1;
        }
        
        return r;
                
    }
}

 

posted on 2013-05-20 17:22  Alan Yang  阅读(212)  评论(1编辑  收藏  举报