Beginner Swift 3: How to find pairs in array that add up to given number

前端 未结 4 1901
深忆病人
深忆病人 2021-01-22 05:40

Need to loop through an array and say whether there are any pairs of numbers that sum to 8

e.g. [1,2,4,4] = yes

Can get it working with lots of nested if stateme

4条回答
  •  灰色年华
    2021-01-22 06:20

    Please try the below code. It will give you all the unique pairs whose sum will be equal to the targetSum. It performs the binary search so will be better in performance. The time complexity of this solution is O(NLogN)

    ((arr,targetSum) => {
    if ((arr && arr.length === 0) || targetSum === undefined) {
        return false;
    } else {
        for (let x = 0; x <=arr.length -1; x++) {
            let partnerInPair = targetSum - arr[x];
            let start = x+1;
            let end = (arr.length) - 2;
    
             while(start <= end) {
                let mid = parseInt(((start + end)/2));
                if (arr[mid] === partnerInPair) {
                    console.log(`Pairs are ${arr[x]} and ${arr[mid]} `);
                    break;
                } else if(partnerInPair < arr[mid]) {
                    end = mid - 1;
                } else if(partnerInPair > arr[mid]) {
                    start = mid + 1;
                }
             }
        };
    
    };
    

    })([0,1,2,3,4,5,6,7,8,9], 10)

提交回复
热议问题