DW组队学习——Task01:数组
两数之和
使用字典,可以大大提高查找效率。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# HashTable -> Dictionary
hashDic = {}
i = 0
while i < len(nums):
if hashDic.has_key(target-nums[i]):
return i,hashDic[target-nums[i]]
hashDic[nums[i]] = i
i = i+1
return
删除有序数组中的重复项
这里一开始一直忽略了特殊情况:数组中至少有一个元素不是重复的,所以可以从下标1开始。
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
l = r = 1
while r < len(nums):
if nums[r] != nums[r-1]:
nums[l]=nums[r]
l+=1
r+=1
return l
移除元素
这题和上面一题差不多,所以很快就写完了。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums:
return 0
index = 0
for i in range(len(nums)):
if nums[i]!=val:
nums[index]=nums[i]
index+=1
return index
三数之和
题目有的难度,一时半会没有想出来。参考了力扣的答案:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
nums.sort()
ans = list()
for first in range(n):
if first > 0 and nums[first] == nums[first - 1]:
continue
third = n - 1
target = -nums[first]
for second in range(first + 1, n):
if second > first + 1 and nums[second] == nums[second - 1]:
continue
while second < third and nums[second] + nums[third] > target:
third -= 1
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])
return ans