Two sum.

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;
                
    }
}
原文地址:https://www.cnblogs.com/anorthwolf/p/3088966.html