leetcode中等.陣列(21-40)python
80. Remove Duplicates from Sorted Array II(m-21)
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) <= 2: return len(nums) cnt = 0 j = 1 for i in xrange(1, len(nums)): if nums[i] == nums[i - 1]: cnt += 1 if cnt < 2: nums[j] = nums[i] j += 1 else: nums[j] = nums[i] j += 1 cnt = 0 return j
81. Search in Rotated Sorted Array II(m-22)
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = start + (end - start) / 2
if nums[mid] == target:
return True
if nums[start] < nums[mid]:
if nums[start] <= target <= nums[mid]:
end = mid
else:
start = mid
elif nums[start] > nums[mid]:
if nums[mid] <= target <= nums[end]:
start = mid
else:
end = mid
else:
start += 1
if nums[start] == target:
return True
if nums[end] == target:
return True
return False
90. Subsets II(m-23)
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(start, nums, path, res, visited):
res.append(path + [])
for i in xrange(start, len(nums)):
if start != i and nums[i] == nums[i - 1]:
continue
if i not in visited:
visited[i] = 1
path.append(nums[i])
dfs(i + 1, nums, path, res, visited)
path.pop()
del visited[i]
nums.sort()
res = []
visited = {}
dfs(0, nums, [], res, visited)
return res
120. Triangle(m-24)
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11).
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
dp = [0] * len(triangle)
dp[0] = triangle[0][0]
for i in range(1, len(triangle)):
pre = dp[0]
for j in range(len(triangle[i])):
tmp = dp[j]
if j == 0:
dp[j] = pre
elif j == len(triangle[i]) - 1:
dp[j] = pre
else:
dp[j] = min(dp[j], pre)
dp[j] += triangle[i][j]
pre = tmp
return min(dp)
380. Insert Delete GetRandom O(1)(m-25)
Design a data structure that supports all following operations in average O(1) time.
insert(val)
: Inserts an item val to the set if not already present.remove(val)
: Removes an item val from the set if present.getRandom
: Returns a random element from current set of elements. Each element must have the same probability of being returned.
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d={}
self.a=[]
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.d:
return False
self.a.append(val)
self.d[val]=len(self.a)-1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.d:
return False
index = self.d[val]
self.a[index] = self.a[-1]
self.d[self.a[-1]] = index
self.a.pop()
del self.d[val]
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.a[random.randrange(0, len(self.a))]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
442.Find All Duplicates in an Array(m-26)
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
class Solution(object):
def ans(self, nums):
res=[]
length=len(nums)
i=0
while i<length:
if nums[i]!=nums[nums[i]-1]:
nums[i], nums[nums[i]-1]=nums[nums[i]-1], nums[i]
else:
i+=1
for i in range(length):
if nums[i]!=i+1:
res.append(nums[i])
return res
495.Teemo Attacking(m-27)
In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.
You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.
class Solution(object):
def findPoisonedDuration(self, timeSeries, duration):
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
if not timeSeries:
return 0
total = len(timeSeries)*duration
for i in range(1, len(timeSeries)):
if timeSeries[i]<timeSeries[i-1]+duration:
total-=timeSeries[i-1]+duration - timeSeries[i]
return total
560. Subarray Sum Equals K(m-28)
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n=len(nums)
d=collections.defaultdict(int)
d[0]=1
sum=0
res=0
for i in range(n):
sum+=nums[i]
if sum-k in d:
res+=d[sum-k]
d[sum]+=1
return res
565. Array Nesting(m-29)
A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.
class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cache=[0]*len(nums)
ans=0
for i, start in enumerate(nums):
if cache[i]:
continue
p=start
length=1
while nums[p]!=start:
cache[nums[p]]!=1
p=nums[p]
length+=1
ans=max(ans, length)
return ans
621. Task Scheduler(m-30)-----
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
611. Valid Triangle Number(m-31)
Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans=0
nums.sort()
for i in range(2, len(nums)):
start=0
end=i-1
while start<end:
if nums[start]+nums[end]>nums[i]:
ans+=end-start
end-=1
else:
start+=1
return ans
670. Maximum Swap(m-32)
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
class Solution:
def maximumSwap(self,num):
b=list(str(num))
list_num=list(map(int,b))#數字的列表形式
list_num_sort=sorted(list_num,reverse=True)#從大到小的排序形式
for i in range(len(list_num)):#找到某一位不是最大數
if list_num[i]<list_num_sort[i]:#第i位不是最大數
break
if i>=len(list_num)-1:#如果i到最後一位仍然是最大數,那麼結束迴圈
return num
else:#我們找到了第i位不是最大的,因此需要找到需要交換的位置,它的值為list_num_sort[i]
index1=i
index2=len(list_num)-1-list_num[::-1].index(list_num_sort[i])
list_num[index1],list_num[index2]=list_num[index2],list_num[index1]
res=list(map(str,list_num))
res=int(''.join(res))
return res