Accepted JavaScript O(n) Solution


  • 0
    K
      var temp;
      var result = [];
      if(nums.length === 2){
        return [0,1];
      }
      else if(target === 0 && nums.indexOf(0) !== -1){
        return [nums.indexOf(0), nums.indexOf(0, nums.indexOf(0)+1)];
      }
      else if(nums.indexOf(target) !== -1 && nums.indexOf(0) !== -1) {
        if(nums.indexOf(target) < nums.indexOf(0)){
          return [nums.indexOf(target), nums.indexOf(0)];
        }
        else {
          return [nums.indexOf(0), nums.indexOf(target)];
        }
      }
      else{
        for(var i = 0; i < nums.length; i++) {
          temp = target - nums[i];
            if(nums.indexOf(temp, i+1) !== -1) {
              result.push(i, nums.indexOf(temp, i+1));
            }
            else {
              continue;
            }
          return result;
        }
      }
    };
    

Log in to reply
 

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