334. Increasing Triplet Subsequence
Question:
Given an integer array nums
, return true
if there exists a triple of indices (i, j, k)
such that i < j < k
and nums[i] < nums[j] < nums[k]
. If no such indices exists, return false
.
Solution:
class Solution:
def increasingTriplet(self, nums):
first = second = float("inf")
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True
return False
Remark: Greedy & Dynamic Updating
Feedback:
Runtime: 568 ms, faster than 95.11% of Python3 online submissions for Increasing Triplet Subsequence.
Memory Usage: 24.7 MB, less than 57.38% of Python3 online submissions for Increasing Triplet Subsequence.
238. Product of Array Except Self
Question:
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n)
time and without using the division operation.
Solution:
class Solution:
def productExceptSelf(self, nums):
a = [1]*len(nums)
left, right = 1, 1
for i in range(len(nums)):
a[i] *= left
a[-1-i] *= right
left *= nums[i]
right *= nums[-1-i]
return a
Remark:
Ex: nums = [-1,1,0,-3,3]
Process: i a[i], a[-1-i], a, left, right
1 1 [1, 1, 1, 1, 1] -1 3
-1 3 [1, -1, 1, 3, 1] -1 -9
9 9 [1, -1, 9, 3, 1] 0 0
0 0 [1, 0, 9, 0, 1] 0 0
0 0 [0, 0, 9, 0, 0] 0 0
Result = [0, 0, 9, 0, 0]
Because every time updates of left and right happen after updates of a[I] and a[-1-i].
And the loop from both sides is quite time-saving.
Feedback:
Runtime: 304 ms, faster than 58.25% of Python3 online submissions for Product of Array Except Self.
Memory Usage: 21.1 MB, less than 83.31% of Python3 online submissions for Product of Array Except Self.
560. Subarray Sum Equals K
Question:
Given an array of integers nums
and an integer k
, return the total number of subarrays whose sum equals to k
.
Solution:
class Solution:
def subarraySum(self, nums, k):
pre = 0
d = {0: 1}
ans = 0
for num in nums:
pre += num
if pre - k in d:
ans += d[pre - k]
if pre not in d:
d[pre] = 1
else:
d[pre] += 1
return ans
Feedback:
Runtime: 344 ms, faster than 54.73% of Python3 online submissions for Subarray Sum Equals K.
Memory Usage: 16.6 MB, less than 84.82% of Python3 online submissions for Subarray Sum Equals K.
To be continued... : )