[LeetCode] 1. Two Sum 刷題筆記
Cathy P

前言

菜鳥的刷題記錄,前端工作兩年後發現很多程式基礎(演算法、資料結構等等)都忘得差不多了,其實當初學生時期的底子也不太紮實。手很生,決定開始上 LeedCode 刷題。
基本上是希望是一個紀錄菜鳥成長的過程的系列文。

題目

LeetCode 題目連結:https://leetcode.com/problems/two-sum/

難度等級:Easy

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.

翻譯:
給一個 nums(int array)和 target(int),找出 nums 陣列中的兩個數值加起來會等於 target,回傳這兩個元素的位置。
一定會有唯一解,不會使用相同的元素兩次。

Example 1:

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

Example 2:

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

Example 3:

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

解題過程

做法:
很單純的跑兩個迴圈,第二個迴圈只從第一個數之後的數開始跑,若兩數相加等於零即為答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[j] + nums[i] === target) {
return [i, j];
}
}
}
};

成績

Runtime: 76 ms (排名:83.53%)
Memory Usage: 38.7 MB (排名:73.70%)

心得

LeetCode 的第一題,單純解出答案不要求效率的話,基本上沒有什麼難度,算是很溫和的試水溫題。