Two sum.

红太狼 2021-11-22 06:44 374阅读 0赞

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/

  1. public int[] twoSum(int[] numbers, int target) {
  2. // Start typing your Java solution below
  3. // DO NOT write main() function
  4. int[] r = {};
  5. if(numbers == null|| numbers.length == 0)
  6. return r;
  7. int n = numbers.length;
  8. r = new int[n];
  9. int count=0;
  10. int i =0,temp= 0;
  11. //set a large array.
  12. int[] binMap = new int[10000];
  13. for(i =0;i<n;i++)
  14. {
  15. temp = target-numbers[i];
  16. if(temp>=0 && (binMap[temp]==1))
  17. {
  18. r[count++]=numbers[i];
  19. r[count++]= temp;
  20. }
  21. binMap[numbers[i]] =1;
  22. }
  23. return r;
  24. }
  25. }

转载于:https://www.cnblogs.com/anorthwolf/archive/2013/05/20/3088966.html

发表评论

表情:
评论列表 (有 0 条评论,374人围观)

还没有评论,来说两句吧...

相关阅读