Commit e1017a70 authored by jiang feng's avatar jiang feng
Browse files

Update 22.py, 24.py, 06.py, 23.py, 26.py, 32.py, 25.py, 11.py, 8.py, 19.py,...

Update 22.py, 24.py, 06.py, 23.py, 26.py, 32.py, 25.py, 11.py, 8.py, 19.py, 18.py, 17.py, 16.py, 15.py, 14.py, 4.py, 46.py, 48.py, 53.py, 45.py, 44.py, 42.py, 60.py, 05.py, 03.py, 41.py, 36.py, 65.py, 34.py, 33.py, 31.py, 70.py, 56.py, 54.py, 73.py, 40.py, 78.py, 30.py, 72.py, 66.py, 64.py, 63.py, 74.py, 81.py, 86.py, 85.py, 83.py, 87.py, 79.py, 93.py, 92.py, 82.py, 94.py, 62.py, TwoSum.py, 90.py, 80.py, 91.py, 67.py, 39.py, 38.py, 71.py, 95.py, 10.py, 75.py, 61.py, 57.py, 97.py, 99.py, 98.py files
parents
'''
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
'''
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
mapSet = {}
start, result = 0, 0
for end in range(len(s)):
if s[end] in mapSet:
start = max(mapSet[s[end]], start)
result = max(result, end-start+1)
mapSet[s[end]] = end+1
return result
\ No newline at end of file
'''
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
dp = [[0 for _ in range(len(s))] for _ in range(len(s))]
maxLength, result = 1, ""
for index in range(len(s)):
dp[index][index] = 1
result = s[index]
length = 2
while length <= len(s):
index_i = 0
while index_i < len(s) - length + 1:
index_j = index_i + length -1
if length == 2 and s[index_i] == s[index_j]:
dp[index_i][index_j] = 1
maxLength = max(maxLength, 2)
result = s[index_i:index_j+1]
elif s[index_i] == s[index_j] and dp[index_i+1][index_j-1]:
dp[index_i][index_j] = 1
if length > maxLength:
maxLength = length
result = s[index_i:index_j+1]
index_i += 1
length += 1
return result
# Space: O(N^2)
# Time: O(N^2)
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def expand(s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right-left-1
start, end = 0, 0
for index in range(len(s)):
even_len = expand(s, index, index+1)
odd_len = expand(s, index, index)
length = max(even_len, odd_len)
if length > (end-start):
start = index - (length-1)/2
end = index +length/2
return s[start:end+1]
\ No newline at end of file
'''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
'''
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
result = ["" for _ in range(numRows)]
row, down = 0, 1
for char in s:
result[row] += char
if row == numRows - 1:
down = 0
if row == 0:
down = 1
if down:
row += 1
else:
row -= 1
final_string = ""
for value in result:
final_string += value
return final_string
print Solution().convert("PAYPALISHIRING",3)
\ No newline at end of file
'''
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
'''
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
dp[0][0] = True
for index in range(1, len(dp[0])):
if p[index-1] == '*':
dp[0][index] = dp[0][index - 2]
for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if s[index_i - 1] == p[index_j - 1] or p[index_j - 1] == '.':
dp[index_i][index_j] = dp[index_i-1][index_j-1]
elif p[index_j-1] == '*':
dp[index_i][index_j] = dp[index_i][index_j-2]
if s[index_i-1] == p[index_j-2] or p[index_j-2] == '.':
dp[index_i][index_j] = dp[index_i-1][index_j] or dp[index_i][index_j]
else:
dp[index_i][index_j] = False
return dp[len(s)][len(p)]
\ No newline at end of file
'''
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
'''
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
left, right, maxArea = 0, len(height) - 1, 0
while left < right:
maxArea = max(maxArea, min(height[left], height[right])*(right-left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return maxArea
# Space : O(1)
# Time: O(N)
\ No newline at end of file
'''
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
def prefix(strs, index):
check_prefix = strs[0][:index]
for index in range(1, len(strs)):
if not strs[index].startswith(check_prefix):
return False
return True
if not strs:
return ""
minLength = float('inf')
for string in strs:
minLength = min(minLength, len(string))
low, high = 0, minLength
while low <= high:
mid = (low+high)/2
if (prefix(strs, mid)):
low = mid + 1
else:
high = mid - 1
return strs[0][:(low+high)/2]
'''
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]
]
'''
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
if (len(nums) >= 3) and (nums[0] == nums[len(nums) -1]) and (nums[0] == 0):
return [[0, 0, 0]]
result = []
for index in range(len(nums) - 1):
left = index+1
right = len(nums) - 1
while left < right:
currSum = nums[index] + nums[left] + nums[right]
if currSum == 0:
result.append([nums[index], nums[left], nums[right]])
left += 1
right -= 1
elif currSum < 0:
left += 1
else:
right -= 1
return [list(t) for t in set(tuple(element) for element in result)]
# Space: O(1)
# Time: O(N^2)
\ No newline at end of file
'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
'''
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result, min_diff = 0, float('inf')
for index in range(len(nums)-1):
left = index + 1
right = len(nums) - 1
while left < right:
currSum = nums[index] + nums[left] + nums[right]
diff = abs(target - currSum)
if diff == 0:
return target
if diff < min_diff:
min_diff = diff
result = currSum
if currSum < target:
left += 1
else:
right -= 1
return result
# Space: O(1)
# Time: O(N^2)
\ No newline at end of file
'''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
'''
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
phoneMap = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7' : 'pqrs', '8': 'tuv', '9':'wxyz'}
number = str(digits)
if number == "":
return []
result = ['']
for char in number:
values = phoneMap[char]
new_result = []
for prefix in result:
currElement = prefix
for value in values:
new_result.append(currElement+value)
result = new_result
# result = [prefix+value for prefix in result for value in values]
return result
print Solution().letterCombinations("23")
\ No newline at end of file
'''
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
'''
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
sumMapping = {}
for index_i in range(len(nums)-1):
for index_j in range(index_i+1, len(nums)):
currSum = nums[index_i] + nums[index_j]
if currSum in sumMapping:
sumMapping[currSum].append((index_i, index_j))
else:
sumMapping[currSum] = [(index_i, index_j)]
result = set()
for key, value in sumMapping.iteritems():
diff = target - key
if diff in sumMapping:
firstSet = value
secondSet = sumMapping[diff]
for (i, j) in firstSet:
for (k, l) in secondSet:
fourlet = [i, j, k, l]
if len(set(fourlet)) != len(fourlet):
continue
fourlist = [nums[i], nums[j], nums[k], nums[l]]
fourlist.sort()
result.add(tuple(fourlist))
return list(result)
# Space : O(N)
# Time: O(N^3)
'''
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head:
return None
ref = head
while n > 0:
ref = ref.next
n -= 1
if ref is None:
return head.next
else:
main = head
while ref.next:
main = main.next
ref = ref.next
main.next = main.next.next
return head
\ No newline at end of file
'''
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
'''
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
def backtracking(S, left, right):
if len(S) == 2*n:
result.append(S)
return
if left < n:
backtracking(S+'(', left+1, right)
if right < left:
backtracking(S+')', left, right+1)
backtracking('', 0, 0)
return result
\ No newline at end of file
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
from heapq import heappush, heappop
heap = []
head = point = ListNode(0)
for element in lists:
if element:
heapq.heappush(heap, (element.val, element))
while heap:
value, node = heapq.heappop(heap)
head.next = ListNode(value)
head = head.next
node = node.next
if node:
heapq.heappush(heap, (node.val, node))
return point.next
# Space: O(K)
# Time: O(N*log(K))
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
def merge2Lists(l1, l2):
head = point = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
point.next = ListNode(l1.val)
l1 = l1.next
else:
point.next = ListNode(l2.val)
l2 = l2.next
point = point.next
if l1:
point.next = l1
else:
point.next = l2
return head.next
if not lists:
return lists
interval = 1
while interval < len(lists):
for index in range(0, len(lists) - interval ,interval*2):
lists[index] = merge2Lists(lists[index], lists[index+interval])
interval *= 2
return lists[0]
# Time: O(N*log(k))
# Space: O(1)
\ No newline at end of file
'''
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
ref = head
while ref is not None and ref.next is not None:
ref.val, ref.next.val = ref.next.val, ref.val
ref = ref.next.next
return head
\ No newline at end of file
'''
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
if head:
slow = head # the mover
while slow:
group = []
while slow and len(group) < k:
group.append(slow)
slow = slow.next
if not slow and len(group) < k:
return head
for i in range(k/2):
print i,k-i-1
group[i].val,group[k-i-1].val = group[k-i-1].val,group[i].val
return head
# Space: O(k)
# Time: O(N)
\ No newline at end of file
'''
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
'''
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
index_i = 0
for index_j in range(1, len(nums)):
if nums[index_i] != nums[index_j]:
index_i += 1
nums[index_i] = nums[index_j]
return index_i + 1
\ No newline at end of file
'''
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodstudentgoodword",
words = ["word","student"]
Output: []
'''
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if not str or not words:
return []
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
result = []
n, numOfWords, fixLen = len(s), len(words),len(words[0])
for index in range(0, n-numOfWords*fixLen+1):
seen = {}
index_j = 0
while index_j < numOfWords:
word = s[index + index_j*fixLen: index + (index_j+1)*fixLen]
if word in counts:
if word in seen:
seen[word] += 1
else:
seen[word] = 1
if seen[word] > counts[word]:
break
else:
break
index_j += 1
if index_j == numOfWords:
result.append(index)
return
# Time: O(N^2)
# Space: O(N)
\ No newline at end of file
'''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
'''
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
index_i = len(nums) - 2
while index_i >= 0 and nums[index_i] >= nums[index_i+1]:
index_i -= 1
if index_i >= 0:
index_j = len(nums) - 1
while index_j >= index_i and nums[index_j] <= nums[index_i]:
index_j -= 1
nums[index_i], nums[index_j] = nums[index_j], nums[index_i]
start = index_i + 1
end = len(nums) - 1
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
\ No newline at end of file
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack, result = [-1], 0
for index in range(len(s)):
if s[index] == '(':
stack.append(index)
else:
currIndex = stack.pop()
if currIndex == -1:
stack.append(index)
else:
result = max(result, index-currIndex+1)
return result
\ No newline at end of file
'''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
'''
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if target >= nums[left] and target <= nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if target >= nums[mid] and target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def searchRecursive(nums, left, right, target):
if left > right:
return -1
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
return searchRecursive(nums, left, mid-1, target)
else:
return searchRecursive(nums, mid+1, right, target)
else:
if nums[mid] < target <= nums[right]:
return searchRecursive(nums, mid+1, right, target)
else:
return searchRecursive(nums, left, mid-1, target)
return searchRecursive(nums, 0, len(nums)-1, target)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment