三数之和
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Code(By myself):
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
count = len(nums)
collect = []
for i in range(count):
left = i+1
right = count-1
#避免重复找同一个数据
if i >0 and nums[i] == nums[i-1]:
left +=1
continue
#数据按小到大排列,每次选取nums[i],在其后寻找符合a + b + c = 0的两个数据
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum == 0:
col = [nums[i],nums[left],nums[right]]
collect.append(col)
left+=1
right-=1
#循环中nums[i]已确定,当再确定1个数时,另一个数也确定,左右端任一端出现重复均可跳过
while nums[left] == nums[left-1] and left < right:
left+=1
while nums[right] == nums[right+1] and left < right:
right-=1
if sum<0:
left+=1
elif sum > 0:
right-=1
return collect
Code(others):
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
l = len(nums)
if l < 3:
return []
nums.sort()
ret = []
#三数相同,只能是0
if nums.count(0) >= 3:
ret.append([0,0,0])
#同正、同负,无结果
if nums[0] >= 0 or nums[-1] <= 0:
return ret
#二数相同
prev = None
doubles = []
for x in nums:
if prev is not None and prev == x and x not in doubles[-1:]:
doubles.append(x)
prev = x
for x in doubles:
if x == 0:
continue
sval = -x*2
if sval in nums:
if sval > 0:
ret.append([x, x, sval])
else:
ret.append([sval, x, x])
#各不相同
nums = list(set(nums))
nums.sort()
print nums
neg_len = abs(nums[0])
pos_len = abs(nums[-1])
max_len = max(neg_len, pos_len)+1
negmaps = [False]*max_len #负数
posmaps = [False]*max_len #正数
for x in nums:
if x < 0:
negmaps[-x] = True
elif x > 0:
posmaps[x] = True
# 包含0
if 0 in nums:
for x in xrange(1, max_len):
if negmaps[x] and posmaps[x]:
ret.append([-x, 0, x])
# 不包含0
sep = None
for i in xrange(len(nums)):
if nums[i] >= 0:
sep = i
break
# 两负一正
for i in xrange(sep):
for j in xrange(sep-1, i, -1):
sval = -(nums[i]+nums[j])
if sval > pos_len:
break
if posmaps[sval]:
ret.append([nums[i], nums[j], sval])
# 两正一负
if nums[sep] == 0:
sep += 1
for i in xrange(sep, len(nums)):
if nums[i]*2 > neg_len:
break
for j in xrange(i+1, len(nums)):
sval = nums[i]+nums[j]
if sval > neg_len:
break
if negmaps[sval]:
ret.append([-sval, nums[i], nums[j]])
return ret
总结:
优化代码减少时间
矩阵置零
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Code(By myself):
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
row = []
cow = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
row.append(i)
cow.append(j)
for i in set(row):
for j in range(len(matrix[i])):
matrix[i][j] = 0
for j in set(cow):
for i in range(len(matrix)):
matrix[i][j] = 0
Code(others):
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
rows = set()
cols = set()
row = len(matrix)
col = len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for i in rows:
for j in range(col):
matrix[i][j] = 0
for j in cols:
for i in range(row):
matrix[i][j] = 0
字母异位词分组
Given an array of strings, group anagrams together.Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Code(By myself):
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dic = {}
for each in strs:
temp = list(each)
temp.sort()
s = ''.join(temp)
if s in dic:
dic[s].append(each)
else:
dic[s] = [each]
return list(dic.values())
Code(others):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
if not strs:
return []
ans = []
d_s_idx = {}
idx = 0
for word in strs:
word_new = "".join(sorted(word))
if word_new in d_s_idx:
ans[d_s_idx[word_new]].append(word)
else:
d_s_idx[word_new] = idx
ans.append([word]) # 不能换成:ans[idx] = [word]
idx += 1
return ans
总结:
str.join()以分隔符连接后面的序列成字符串。
Given a string, find the length of the longest substring without repeating characters.
Example:
Given "abcabcbb", the answer is "abc", which the length is 3.
Code(By myself):
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
result = s[0]
j = 1
temp = s[0]
while j < length:
if s[j] not in temp:
temp = temp + s[j]
j += 1
else:
while s[j] in temp:
temp = temp[1:]
temp = temp + s[j]
j += 1
if len(temp) > len(result):
result = temp
return len(result)
Code(others):
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxLength = 0
length = 0
subStr = {}
for i, char in enumerate(s):
if char in subStr:
if i - subStr[char] > length:
length += 1
maxLength = length if length > maxLength else maxLength
else:
length = i - subStr[char]
else:
length += 1
maxLength = length if length > maxLength else maxLength
subStr[char] = i
return maxLength
总结:
enumerate()是python内置函数,在字典上是枚举的意思,对于一个可迭代/遍历的对象,enumerate()将其组成索引序列,利用它可以同时获得索引和值
最长回文字串
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Code(By myself):
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
maxStr = ''
for i in range(len(s)):
x = 1
while x + i < len(s) and i - x >= 0:
if s[i-x] == s[i+x]:
x += 1
else:
break
if x + i < len(s) and i - x >= 0 and s[i-x] == s[i+x]:
if 2 * x + 1 > len(maxStr):
maxStr = s[:]
else:
if 2 * x - 1 > len(maxStr):
maxStr = s[i-x+1:i+x]
x = 0
while x + i + 1 <len(s) and i - x >= 0:
if s[i-x] == s[i+1+x]:
x += 1
else:
break
if x + i + 1 <len(s) and i - x >= 0 and s[i-x] == s[i+1+x]:
if 2 * x + 2 > len(maxStr):
maxStr = s[:]
else:
if 2 * x > len(maxStr):
maxStr = s[i-x+1:i+x+1]
return maxStr
Code(others):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if s == s[::-1]:
return s
maxlen = 1
start = 0
for i in xrange(len(s)):
if i - maxlen >= 1 and s[i-maxlen-1:i+1] == s[i-maxlen-1:i+1][::-1]:
start = i - maxlen - 1
maxlen += 2
continue
if i - maxlen >= 0 and s[i-maxlen:i+1] == s[i-maxlen:i+1][::-1]:
start = i - maxlen
maxlen += 1
return s[start:start+maxlen]
递增的三元子序列
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
Example:
Given [1, 2, 3, 4, 5],
return true.
Code(By myself):
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) < 3:
return False
temp = [nums[0], float("inf")]
for i in range(1,len(nums)):
if nums[i] > temp[1]:
return True
if nums[i] > min(nums[0:i]):
if nums[i] < temp[1]:
temp = [min(nums[0:i]),nums[i]]
return False
Code(others):
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
import sys
a=sys.maxint
b=sys.maxint
for i in nums:
if(i<=a): a=i
elif (i<=b):b=i
else: return True
return False
总结:
善用两个指针和条件语句