研究生已經上了四個月有余,終于決定要寫點東西了。
以往覺得寫作和我的生活肯定沒有任何交集。但是最近通過和朋友的交流加上自己對生活的一些感悟,讓我覺得,記錄生活中的點點滴滴是每個人生命的義務之一。不管是知識,或是生活中的小感悟,它們都不僅能夠讓我們得到溫故而知新的感覺,更能讓自己在記錄這件事本身不經意間得到某種意義的升華。
我選擇從最近一直在做的一件事開始,那就是刷Leetcode上的題目。總的來說,這個程序員人盡皆知的網站上的題目,有難有易,有些讓人絞盡腦汁,有些也能很快解出來。但是很大一部分時間,我是從別人那里汲取到智慧的養分,然后拍案叫絕而題解的。今天寫這些東西,是因為我希望我也能很開心地做一個傳遞者,把Eureka的瞬間傳遞給盡量多的人,同時也讓自己回顧之前的一些東西,避免遺忘,也方便以后自己查找。那么,現在開始吧。
(一部分程序用python,一部分用java,按照題號來)
1.Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
大意給出一個數字target,并在一個數組里找到兩個數的加和正好等于target,并返回這兩個數所在的index(注意index要加1)。
這個題目最簡單的解法就是建立一個字典,并循環數組中每個元素,把target - nums[i](當前訪問元素的值)作為字典的key,當前的index作為該key的value。同時,如果訪問到的元素已經在字典中作為key存在,說明這個值正好等于之前target - nums[i]的值,返回兩個index即可。
# python code:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(0,len(nums)):
if nums[i] in d:
return [d[nums[i]], i + 1]
else:
d[target - nums[i]] = i + 1
當然這道題還有其他解法,在后面有3 sum,還有 3sum closest還會介紹。