Given an integer array nums and a target value target with the JS method, find the two integers whose sum is the target value in the array, and return their array subscripts

Given an integer array nums and a target value target with the JS method, find the two integers whose sum is the target value in the array, and return their array subscripts.

Topic description:

Given an array of integers and a target value, find the two numbers in the array that sum to the target value.
You can assume that each input corresponds to only one answer, and the same elements cannot be reused.
Example: Given nums = [2, 7, 11, 15], target = 9
returns [0, 1]

Specific code:

<script>
        var  nums = [2, 7, 11, 15], target = 9;
        function returnIndex(nums,target){
            var len=nums.length;
            var back=[];
            for(var i=0;i<len-1;i++){
                for(var j=i+1;j<len;j++){
                    if(nums[i]+nums[j]==target){
                        back[0]=i;
                        back[1]=j
                    }
                }

            }
            return back
        }
            
        var a=returnIndex(nums,target)
        console.log(a)
    </script>

Guess you like

Origin blog.csdn.net/weixin_44401636/article/details/89327789