[LeetCode]-[JavaScript]-[解題]-1.Two Sum

文、意如

題目精簡說明:

給兩個參數(參數一為數字陣列、參數二為目標數字)

陣列中其中兩個數字加起來等於目標數字(數字不能自己加自己)

回傳陣列為:這兩個數字的位置

原始題目:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6 Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6 Output: [0,1]

參考程式碼:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */

var twoSum = function(nums, target) {
   
   var ss=nums.length;
   var myarr=[];
   for(var i=0;i<ss;i++){ //第一個數字位置
    for(var j=1;j<ss;j++){ //第二個數字位置
       if(i!=j){//自己不能加自己
        if(nums[i]+nums[j]==target){ //兩個數字位置的值加起來等於目標數字
          myarr=[i,j] //把加起來的數字等於目標值的位置存成陣列
          return myarr//回傳陣列
        }
       }
     }
   }
 
};

YiruAtStudio - 關於我 - 意如