@min9nim/

binary-search

Nodejs

No description

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function binarySearch(arr, val, s, e){
    if(s > e){
        return null;
    }
    var c = Math.floor((s+e)/2);
    if(arr[c].val === val){
        return arr[c].id;
    }else if(arr[c].val > val){
        return binarySearch(arr, val, s, c-1);
    }else if(arr[c].val < val){
        return binarySearch(arr, val, c+1, e);
    }
}

function whatFlavors(cost, m){
    var costObj = cost.map((c,i) => {return {val: c, id: i+1};});
    costObj.sort((a,b)=>a.val-b.val);
    for(var i=0; i<costObj.length-1; i++){
        var id2 = binarySearch(costObj, m-costObj[i].val, i+1, costObj.length-1);
        if(id2){
            var id1 = costObj[i].id;
            console.log(Math.min(id1, id2) + " " + Math.max(id1, id2));
            return;
        }
    }
}

whatFlavors([1,7,9,5,8], 12);
node v10.16.0