LeetCode 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.

题意

阵列中两个元素相加若等於target,回传元素的索引值。

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [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]

解题想法

使用双回圈,遍历元素,若相加等於target,回传索引值。

Solution

var twoSum = function(nums, target) {
    let len = nums.length
    for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            if (nums[i] + nums[j] === target)
                return [i, j];
        }
    }
};

<<:  [VR 前後端交响曲Day29] Rails专案开发 - Action Cable即时互动功能: 以edit和delete ticket为例

>>:  (31) 试着学 Hexo - 番外篇之常见问题

[Refactoring] Chapter 1 Refactoring: A First Example - RPG Game Hunting Mission

本篇同步发布於个人Blog: [Refactoring] Chapter 1 Refactoring...

[Day 29] LeetCode - 242 Valid Anagram

本篇同步发布於Blog:[解题] LeetCode - 242 Valid Anagram 平台: ...

LeetCode解题 Day06

1629. Slowest Key https://leetcode.com/problems/sl...

[Day01] 学了 React 後的下一步?准备好两把刷子!

学了 React 之後的下一步,还能学什麽呢? 在今年的铁人赛中,想要来分享这一两年来开始使用的 T...

Python & GCP 学习笔记_Gmail API 操作

最近在一个偶然的情况下接触到 Gmail API 因此找了一个周末来好好研究一下该怎麽操作他 以下是...