Find 2 numbers in an unsorted array equal to a given sum

前端 未结 18 903
太阳男子
太阳男子 2020-11-29 19:56

We need to find pair of numbers in an array whose sum is equal to a given value.

A = {6,4,5,7,9,1,2}

Sum = 10 Then the pairs are - {6,4} ,

18条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 20:41

    if its a sorted array and we need only pair of numbers and not all the pairs we can do it like this:

    public void sums(int a[] , int x){ // A = 1,2,3,9,11,20 x=11
        int i=0 , j=a.length-1;
        while(i < j){
          if(a[i] + a[j] == x) system.out.println("the numbers : "a[x] + " " + a[y]);
          else if(a[i] + a[j] < x) i++;
          else j--;
        }
    }
    

    1 2 3 9 11 20 || i=0 , j=5 sum=21 x=11
    1 2 3 9 11 20 || i=0 , j=4 sum=13 x=11
    1 2 3 9 11 20 || i=0 , j=4 sum=11 x=11
    END

提交回复
热议问题