LeetCode Online Judge
https://leetcode.com/
1.Contain With Most Water [96ms]
#方法1:头尾指针,比较头尾两块板的高度,当low小于high的时候
#如果 high--并不会增加容量,所以low++,遍历取最大值
class Solution(object):
def maxArea(self, height):
low, high = 0, len(height) - 1
ans = 0
if high+1 < 2 :
return 0
while low < high :
area = (high - low) * min(height[low], height[high])
ans = max(ans, area)
if height[low] > height[high] :
high -= 1
else :
low += 1
return ans
2.Find Minimum In Rotated Array II [64ms]
#方法1:二分,不能判断就 low += 1,这里用了很多的min,应该可以优化
#方法2:Java版本的,while循环限制了 nums[low] > nums[high],默认一定是旋转的,这样可以直接返回nums[low]
class Solution(object):
def findMin(self, nums):
ans = 1000000
low, high = 0, len(nums) - 1
while low < high :
mid = int((low + high) / 2)
ans = min(ans, nums[mid])
if nums[low] < nums[mid] :
ans = min(ans, nums[low])
low = mid + 1
elif nums[low] > nums[mid] :
ans = min(ans, nums[mid])
high = mid
else :
low += 1
ans = min(ans, nums[low])
return ans
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.empty())
return 0;
if(nums.size() == 1)
return nums[0];
int n = nums.size();
int low = 0;
int high = n-1;
while(low < high && nums[low] >= nums[high])
{
int mid = low + (high-low)/2;
if(nums[mid] < nums[low]) // mid is in second part
high = mid;
else if(nums[mid] == nums[low])
low ++;
else
low = mid+1;
}
return nums[low];
}
};
3.Find The Duplicate Number [56ms]
#方法1:回环检测法,膜拜大神,但感觉限制条件蛮多的 [56ms]
#方法2:二分法加鸽巢原理 [98ms]
class Solution(object):
def findDuplicate(self, nums):
# slow指针每次走一步,fast指针每次走两步
slow, fast = 0, 0
#检测回环入口,但是不知道那个是目标数
while True :
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast :
break
#找打重复的目标
find = 0
while True :
slow = nums[slow]
find = nums[find]
if slow == find :
return slow
class Solution(object):
def findDuplicate(self, nums):
lth = len(nums)
low, high = 0, lth - 1
while low <= high :
mid = int((low + high) / 2)
cnt = 0
#计算小于中间数的个数
for i in range(lth) :
if nums[i] <= mid :
cnt += 1
#如果计算值大于中位数,则肯定在前半部分
if cnt > mid :
high = mid - 1
else :
low = mid + 1
return low
4.Insert Delete GetRandom O(1) [576ms]
#方法1:用python内置的字典结构
#或者用一个数组和一个哈希表的结构
#数组用来储存数和生成随机数
#哈希表记录值的位置,删除需要把它换到后面
#判断是否在键值内,数下键值的数目判断就可以
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
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 not self.d.has_key(str(val)) :
self.d[str(val)] = val
return True
else :
return False
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 self.d.has_key(str(val)) :
del self.d[str(val)]
return True
else :
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
import random
keys = list(self.d.keys())
lth = len(keys)
if lth == 0 :
return None
else :
r = random.randint(0, lth-1)
return self.d[keys[r]]
# 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()
5.Longest Consecutive Sequence [40ms]
#方法1:先取出一个元素,然后向两边扩展,记得遍历完删除,保证O(n)复杂度
# 用while uni 比 用for 更省事
# 用set 比 用自己建的{}更省事
# set有pop方法和remove方法
class Solution(object):
def longestConsecutive(self, nums):
uni = set(nums)
ans = 0
while uni :
n = uni.pop()
left = n - 1
right = n + 1
count = 1
while left in uni :
uni.remove(left)
left -= 1
count += 1
while right in uni :
uni.remove(right)
right += 1
count += 1
ans = max(ans, count)
return ans
6.Next Permutation [72ms]
#方法1:参照网上的方法
#注意的地方是切片的resvece方法无效和逆序的写法
class Solution(object):
def nextPermutation(self, nums):
lth = len(nums)
flag = -1
#从右到左找到第一个打破升序的位置flag
for i in range(lth-1, 0, -1) :
if nums[i-1] < nums[i] :
flag = i - 1
break
if flag < 0 :
nums.reverse()
return
#从右到左找到第一个比打破位置大的数
for i in range(lth-1, -1, -1) :
if nums[i] > nums[flag] :
nums[i], nums[flag] = nums[flag], nums[i]
break
#从flag+1开始后面逆序
start, end = flag+1, lth-1
while start < end :
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
7.Trapping Rain Water [57ms]
#方法1:能装多少水取决于左右最大的高度,最后判断是否为正其实是看它是不是边界 [80ms]
#方法2:从两边开始搜索,次高那边往里缩,因为水面由次高决定,有最高在肯定水面能达到次高 [57ms]
class Solution(object):
def trap(self, height):
lth = len(height)
maxheight = 0
leftmax = [0 for i in range(lth)]
for i in range(lth) :
leftmax[i] = maxheight
maxheight = maxheight if maxheight > height[i] else height[i]
maxheight = 0
rightmax = [0 for i in range(lth)]
for i in range(lth-1, -1, -1) :
rightmax[i] = maxheight
maxheight = maxheight if maxheight > height[i] else height[i]
water = 0
for i in range(lth) :
tmp = min(leftmax[i], rightmax[i]) - height[i]
if tmp > 0 :
water += tmp
return water
class Solution(object):
def trap(self, height):
secHeight = 0
left, right = 0, len(height) - 1
water = 0
while left < right :
if height[left] < height[right] :
secHeight = max(height[left], secHeight)
water += secHeight - height[left]
left += 1
else :
secHeight = max(height[right], secHeight)
water += secHeight - height[right]
right -= 1
return water