羞于post鸿竖,但勇于丟臉武花。
本系列將記錄渣渣成長之路圆凰,目的主要為個人的刷題思路總結(jié)。
目前默認language:Python体箕。
題目Description:Two Sum
Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.
You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].
思路1:
遍歷加和专钉。
class Solution(object):
def twoSum(self, nums, target):
a = 0;
while (a < len(nums) ):
for x in nums:
for y in nums:
result = x + y
if (result == target ) & (nums.index(x) <> nums.index(y)):
return (nums.index(x),nums.index(y))
a = a + 1
結(jié)果:Time Limit Exceeded
思路2:
參考思路3的方法,遍歷索引累铅。
class Solution(object):
def twoSum(self, nums, target):
for x in range(len(nums)):
if target - nums[x] in nums:
if x <> nums.index(target - nums[x]):
return [x,nums.index(target - nums[x])]
思路3:(參考solution跃须,來源如圖)
我當(dāng)前還沒搞懂這個答案……
/**
* 本代碼由九章算法編輯提供。版權(quán)所有娃兽,轉(zhuǎn)發(fā)請注明出處菇民。
* - 九章算法致力于幫助更多中國人找到好的工作,教師團隊均來自硅谷和國內(nèi)的一線大公司在職工程師。
* - 現(xiàn)有的面試培訓(xùn)課程包括:九章算法班第练,系統(tǒng)設(shè)計班阔馋,算法強化班,Java入門與基礎(chǔ)算法班娇掏,Android 項目實戰(zhàn)班呕寝,Big Data 項目實戰(zhàn)班,
* - 更多詳情請見官方網(wǎng)站:http://www.jiuzhang.com/?source=code
*/
public class Solution {
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1 + 1, index2 + 1] (index1 < index2)
numbers=[2, 7, 11, 15], target=9
return [1, 2]
*/
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (map.get(numbers[i]) != null) {
int[] result = {map.get(numbers[i]) + 1, i + 1};
return result;
}
map.put(target - numbers[i], i);
}
int[] result = {};
return result;
}
}