标签:solution pointer ctc arch 问题 sea efi cte har
@2017.06.04
from heapq import * class Solution: # @param matrix: a matrix of integers # @param k: an integer # @return: the kth smallest number in the matrix def kthSmallest(self, matrix, k): # write your code here if not matrix or not matrix[0] or k <= 0: return rowNum, colNum = len(matrix), len(matrix[0]) if rowNum * colNum < k: return kth, heap, visited = 0, [], set([(0, 0)]) heappush(heap, (matrix[0][0], 0, 0)) xPath, yPath = [1, 0], [0, 1] # go right or go down to get the next one while kth < k - 1 and heap: val, row, col = heappop(heap) kth += 1 for i in range(2): x = row + xPath[i] y = col + yPath[i] if x < rowNum and y < colNum and (x, y) not in visited: heappush(heap, (matrix[x][y], x, y)) visited.add((x, y)) return heappop(heap)[0]
class Solution: # @param nums: a list of integers # @param s: an integer # @return: an integer representing the minimum size of subarray def minimumSize(self, nums, s): # write your code here if not nums or s <= 0: return -1 j, subSum, length = 0, 0, sys.maxint for i in range(len(nums)): while j < len(nums) and subSum < s: subSum += nums[j] j += 1 if subSum >= s and j - i < length: length = j - i subSum -= nums[i] return -1 if length == sys.maxint else length
class Solution: # @param s: a string # @return: an integer def lengthOfLongestSubstring(self, s): # write your code here if not s: return 0 cnt, i, j, ans = 0, 0, 0, 1 charAt = [0] * 256 while j < len(s): while j < len(s) and not charAt[ord(s[j])]: cnt += 1 charAt[ord(s[j])] += 1 j += 1 ans = max(ans, j - i) charAt[ord(s[i])] -= 1 i += 1 return ans
class Solution: # @param s : A string # @return : An integer def lengthOfLongestSubstringKDistinct(self, s, k): # write your code here if not s or k <= 0: return 0 i, j, distinctCount, ans = 0, 0, 0, 1 hashTable = {} while j < len(s): while j < len(s) and (s[j] in hashTable or distinctCount < k): if s[j] in hashTable: hashTable[s[j]] += 1 j += 1 else: hashTable[s[j]] = 1 j += 1 distinctCount += 1 ans = max(ans, j - i) hashTable[s[i]] -= 1 if not hashTable[s[i]]: hashTable.pop(s[i]) distinctCount -= 1 i += 1 return ans
from heapq import * class Solution: # @param {int[]} A an integer arrays sorted in ascending order # @param {int[]} B an integer arrays sorted in ascending order # @param {int} k an integer # @return {int} an integer def kthSmallestSum(self, A, B, k): # Write your code here if not A or not B or k <= 0 or k > len(A) * len(B): return heap = [(A[0] + B[0], 0, 0)] APath, BPath = [0, 1], [1, 0] visited = set((0, 0)) kth = 0 while heap and kth < k - 1: val, indA, indB = heappop(heap) kth += 1 for i in range(2): newA, newB = indA + APath[i], indB + BPath[i] if newA < len(A) and newB < len(B) and (newA, newB) not in visited: heappush(heap, (A[newA] + B[newB], newA, newB)) visited.add((newA, newB)) return heappop(heap)[0]
标签:solution pointer ctc arch 问题 sea efi cte har
原文地址:http://www.cnblogs.com/wttttt/p/6941247.html