My code is Time out。I will do what????


  • 0
    X

    public int[] twoSum(int[] numbers, int target) {
    int[] ok=new int[2];
    int a,b;
    int i=numbers.length;
    for(int n=0;n<i;n++){
    for(int m=n;m<i;m++){
    int sum=numbers[n]+numbers[m];
    if(target==sum){
    ok[0]=(n<m?n:m)+1;
    ok[1]=(n>m?n:m)+1;
    break;
    }
    }
    }
    return ok;
    }


  • 5
    S

    Your code runs in O(n^2) whereas a O(n) solution is expected for this problem. One such solution is to put all numbers in a hash table, then for each number N, search if its complement (i.e. sum - N) is in the hash table. If so, then N and sum - N is the pair of numbers that satisfy the requirement.

    Please format your code properly and add comments to explain your thoughts next time.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.