本篇整理的爲Array算法題(Easy級別)的第二部分,這些題對我而言更有啓發性,提高了思維的靈活性。如有紕漏,敬請指出,也歡迎交流分享更好的算法~。
1. Two Sum
題目簡介:給定一串數(nums)和一個目標數(target),要求找出nums中相加之和爲target的兩個數的下標。nums中有且僅有一對滿足的數,並且用同一個數兩次。
解題思路:利用字典,對nums中的數(假設當前數爲n)依次進行判斷,若target-n在字典中,說明n和target-n就是滿足條件的兩個數。代碼如下(最多一輪遍歷即可得出結果):
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in xrange(len(nums)):
t = target - nums[i]
if d.has_key(t):
return [d.get(t),i]
d[nums[i]] = i
121. Best Time to Buy and Sell Stock
題目簡介:給定一串數字prices,代表某股票在各日的價格,若你最多能進行一次交易(買進一次賣出一次),求最大收益。解題思路:一輪遍歷,依次判斷當前價格是否爲歷史最低價格,如果是,則更新最低價格,否則,計算當前價格與歷史最低價格之差,表示依次買進賣出所得收益,並判斷該收益是否比之前大,若是,則更新。通過繪製prices的折線圖,可更直觀的理解該解法。代碼如下:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
l = len(prices)
if l < 2:
return 0
valleyPrice = prices[0]
profit = 0
for p in prices:
if p < valleyPrice:
valleyPrice = p
else:
t = p - valleyPrice
if t > profit:
profit = t
return profit
122. Best Time to Buy and Sell Stock II
題目簡介:主題幹如上題,只是用戶可進行多次交易而非一次來獲取收益,求最大收益。
解題思路:類似於上題,畫出價格折線圖,易知只要後一天的價格高於前一天,我們就可以累加差量,得到最後結果。代碼如下:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in xrange(len(prices)-1):
profit+=max(0,prices[i+1]-prices[i])
return profit
167. Two Sum II - Input array is sorted
題目簡介:同1. Two Sum,只是此時的數組已按升序排列。
解題思路:數組有序是個很重要的性質。我們可以採取從數組兩端向中間聚攏的方式找到所需解。若兩端的數之和小於目標數,說明左邊的數應該變大;若兩端的數之和大於目標數,說明右邊的數過大,需要減小,即向左移動;否則,找到所需解。代碼入下:
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left,right = 0,len(numbers)-1
while left < right:
t = numbers[left]+numbers[right]
if t == target:
return [left+1,right+1]
elif t < target:
left+=1
else:
right-=1
169. Majority Element
題目簡介:給定一串數,找出其中個數多於數組長度一半的數。題目限制:滿足條件的數有且只有一個。解題思路:先對數組排序,滿足條件的數肯定處於新數組的中間位置。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sorted(nums)[len(nums)/2]
268. Missing Number
題目簡介:給定一串長爲n的數字數組nums,其中的元素取值爲0~n中的數,且無重複元素,求nums中缺失的那個數。
解題思路:如果眼睛盯死在對數組操作上,難以找到非常方便的解法。將其換算成數學問題的話,複雜度頓時下降。代碼如下:
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
return l*(l+1)//2-sum(nums)
532. K-diff Pairs in an Array
題目簡介:給定一串數,求數中滿足相差爲k的數對(i,j)的個數,(i,j)=(j,i)且不重複計數不同位置的相同元素。解題思路:首先分類討論k的情況。若k<0,則直接返回0;k=0,返回重複元素的個數;k>0,可通過求集合的交集來判斷滿足條件的數對的個數。代碼如下:
import collections
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
if not k:
return sum([v > 1 for v in collections.Counter(nums).values()])
return len(set(nums)&{n+k for n in nums})
643. Maximum Average Subarray I
題目簡介:給定一串數nums和數字k,返回長爲k的子串的最大平均大小。解題思路:窮舉遍歷所有可能的長爲k的子串,k很大時會相當耗時。所以通過滑動寬爲k的窗口,通過減去前一個數和加上後一個數的操作,即可得到當前子串的大小。代碼如下:
class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
l = len(nums)
maxSum = sum(nums[:k])
t = maxSum
for i in xrange(1,l-k+1):
t = t - nums[i-1] + nums[i+k-1]
if t > maxSum:
maxSum = t
return 1.0*maxSum/k