标签:odi 给定一个整数数组 忽略 理解 str 偶数 交集 origin 程序
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ if len(nums1) > len(nums2): return self.intersect(nums2, nums1) hash_map = {} for num in nums1: if num not in hash_map: hash_map[num] = 1 else: hash_map[num] += 1 result = [] for num in nums2: if num in hash_map and hash_map[num] > 0: result.append(num) hash_map[num] -= 1 return result
class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ intervals.sort(key=lambda x: x[0]) result = [intervals[0]] if len(intervals) > 0 else [] n = len(intervals) for i in xrange(1, n): if intervals[i][0] <= result[-1][1]: if intervals[i][1] > result[-1][1]: result[-1][1] = intervals[i][1] else: result.append(intervals[i]) return result
class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ n = len(intervals) result = [] flag = True for i in xrange(0, n): if flag: if newInterval[1] < intervals[i][0]: flag = False result.append(newInterval) result.append(intervals[i]) elif newInterval[0] > intervals[i][1]: result.append(intervals[i]) else: result.append([min(intervals[i][0], newInterval[0]), max(intervals[i][1], newInterval[1])]) flag = False else: if intervals[i][0] <= result[-1][1]: result[-1][1] = max(intervals[i][1], result[-1][1]) else: result.append(intervals[i]) break if flag: result.append(newInterval) else: result.extend(intervals[i+1:]) return result
二分法:
class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ n = len(intervals) result = [] def find_max_less(index): i = 0 j = n-1 while i <= j: mid = (i+j)/2 if intervals[mid][0] == newInterval[index]: return mid elif intervals[mid][0] > newInterval[index]: j = mid - 1 else: if mid+1 >= n or intervals[mid+1][0] > newInterval[index]: return mid else: i = mid + 1 return -1 start = find_max_less(0) end = find_max_less(1) if start == end: if start == -1: intervals.insert(0, newInterval) elif newInterval[0] > intervals[start][1]: intervals.insert(start+1, newInterval) else: intervals[start][1] = max(intervals[start][1], newInterval[1]) else: if start == -1 or newInterval[0] > intervals[start][1]: start += 1 intervals[start][0] = newInterval[0] intervals[start][1] = max(intervals[end][1], newInterval[1]) result.extend(intervals[0:start+1]) result.extend(intervals[end+1:]) return result if result else intervals
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ n = len(nums) red_point = 0 white_point = 0 blue_point = n-1 while white_point <= blue_point: if nums[white_point] == 0: while red_point < white_point: if nums[red_point] == 0: red_point += 1 else: break if red_point < white_point: nums[white_point] = nums[red_point] nums[red_point] = 0 red_point += 1 else: white_point += 1 elif nums[white_point] == 2: while blue_point > white_point: if nums[blue_point] == 2: blue_point -= 1 else: break if blue_point > white_point: nums[white_point] = nums[blue_point] nums[blue_point] = 2 blue_point -= 1 else: white_point += 1 else: white_point += 1 return nums
实现2:
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ red_point = cur_point = 0 blue_point = len(nums)-1 while cur_point <= blue_point: if nums[cur_point] == 0: nums[cur_point], nums[red_point] = nums[red_point], nums[cur_point] red_point += 1 cur_point += 1 elif nums[cur_point] == 2: nums[cur_point], nums[blue_point] = nums[blue_point], nums[cur_point] blue_point -= 1 else: cur_point += 1 return nums
class Solution(object): def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ def custom_cmp(x, y): if x == y: return 0 x += y y += x all_len = len(x) for cur in xrange(all_len): if x[cur] < y[cur]: return -1 elif x[cur] > y[cur]: return 1 return 0 str_nums = [str(num) for num in nums] str_nums.sort(cmp=custom_cmp, reverse=True) if len(str_nums) == 0 or str_nums[0] == "0": return "0" return "".join(str_nums)
class Solution(object): def maximumGap(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n <= 1: return 0 max_num = max(nums) min_num = min(nums) bucket_size = int(math.ceil(float(max_num - min_num) / (n-1))) bucket_size = bucket_size if bucket_size > 0 else 1 bucket_num = (max_num - min_num) / bucket_size + 1 buckets = [None]*bucket_num for num in nums: bucket_index = (num-min_num)/bucket_size if buckets[bucket_index] is None: buckets[bucket_index] = {‘max_num‘:num, ‘min_num‘:num} else: buckets[bucket_index][‘max_num‘] = max(buckets[bucket_index][‘max_num‘], num) buckets[bucket_index][‘min_num‘] = min(buckets[bucket_index][‘min_num‘], num) max_interval = 0 pre_bucket_max = buckets[0][‘max_num‘] for i in xrange(1, bucket_num): if buckets[i] is not None: max_interval = max(max_interval, buckets[i][‘min_num‘]-pre_bucket_max) pre_bucket_max = buckets[i][‘max_num‘] return max_interval
提交代码(桶排序):
class Solution(object): def maximumGap(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n <= 1: return 0 max_num = max(nums) min_num = min(nums) bucket_size = int(math.ceil(float(max_num - min_num) / (n-1))) bucket_size = bucket_size if bucket_size > 0 else 1 bucket_num = (max_num - min_num) / bucket_size + 1 buckets = [None]*bucket_num for num in nums: bucket_index = (num-min_num)/bucket_size if buckets[bucket_index] is None: buckets[bucket_index] = {‘max_num‘:num, ‘min_num‘:num} else: buckets[bucket_index][‘max_num‘] = max(buckets[bucket_index][‘max_num‘], num) buckets[bucket_index][‘min_num‘] = min(buckets[bucket_index][‘min_num‘], num) max_interval = 0 pre_bucket_max = buckets[0][‘max_num‘] for i in xrange(1, bucket_num): if buckets[i] is not None: max_interval = max(max_interval, buckets[i][‘min_num‘]-pre_bucket_max) pre_bucket_max = buckets[i][‘max_num‘] return max_interval
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ citations.sort() max_h = 0 n = len(citations) start = 0 end = n-1 while start <= end: mid = (start + end) / 2 tmp_n = n - mid tmp_value = citations[mid] if tmp_value < tmp_n: start = mid + 1 else: max_h = max(max_h, tmp_n) end = mid - 1 return max_h
提交代码(基数排序):
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ n = len(citations) count = [0]*(n+1) for num in citations: count[min(num, n)] += 1 tmp_n = 0 for k in xrange(n, -1, -1): tmp_n += count[k] if k <= tmp_n: break return k
class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) tmp_nums = [0]*n index_map = range(n) tmp_index = [0]*n results = [0]*n self.divide_combine_alg(nums, tmp_nums, index_map, tmp_index, results, 0, n-1) return results def divide_combine_alg(self, nums, tmp_nums, index_map, tmp_index, results, start, end): if end > start: mid =(start + end)/2 self.divide_combine_alg(nums, tmp_nums, index_map, tmp_index, results, start, mid) self.divide_combine_alg(nums, tmp_nums, index_map, tmp_index, results, mid+1, end) i = start j = mid+1 count = start while i <= mid and j <= end: if nums[i] <= nums[j]: tmp_nums[count] = nums[i] tmp_index[count] = index_map[i] results[index_map[i]] += (j-mid-1) i += 1 else: tmp_nums[count] = nums[j] tmp_index[count] = index_map[j] j += 1 count += 1 while i <= mid: tmp_nums[count] = nums[i] tmp_index[count] = index_map[i] count += 1 results[index_map[i]] += (end-mid) i += 1 while j <= end: tmp_nums[count] = nums[j] tmp_index[count] = index_map[j] count += 1 j += 1 for i in xrange(start, end+1): nums[i] = tmp_nums[i] index_map[i] = tmp_index[i]
提交代码(看了别人的索引数组写的,没改变原数组,对下标排序):
class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) indexes = range(n) tmp_index = [0]*n results = [0]*n self.divide_combine_alg(nums, indexes, tmp_index, results, 0, n-1) return results def divide_combine_alg(self, nums, indexes, tmp_index, results, start, end): if end > start: mid =(start + end)/2 self.divide_combine_alg(nums, indexes, tmp_index, results, start, mid) self.divide_combine_alg(nums, indexes, tmp_index, results, mid+1, end) l = start r = mid+1 for count in xrange(start, end+1): if l > mid: tmp_index[count] = indexes[r] r += 1 elif r > end: tmp_index[count] = indexes[l] results[indexes[l]] += (end-mid) l += 1 elif nums[indexes[l]] <= nums[indexes[r]]: tmp_index[count] = indexes[l] results[indexes[l]] += (r-mid-1) l += 1 else: tmp_index[count] = indexes[r] r += 1 for i in xrange(start, end+1): indexes[i] = tmp_index[i]
class Solution(object): def kClosest(self, points, K): """ :type points: List[List[int]] :type K: int :rtype: List[List[int]] """ n = len(points) start = 0 end = n - 1 while True: org_start = start org_end = end tmp_list = [points[start][0], points[start][1]] tmp = points[start][0] * points[start][0] + points[start][1] * points[start][1] while start < end: while start < end and points[end][0] * points[end][0] + points[end][1] * points[end][1] >= tmp: end -= 1 if start < end: points[start][0], points[start][1] = points[end][0], points[end][1] start += 1 while start < end and points[start][0] * points[start][0] + points[start][1] * points[start][1] <= tmp: start += 1 if start < end: points[end][0], points[end][1] = points[start][0], points[start][1] end -= 1 points[start][0], points[start][1] = tmp_list[0], tmp_list[1] if start == K-1: return points[:K] elif start < K-1: start += 1 end = org_end else: end = end - 1 start = org_start
class Solution(object): def reorganizeString(self, S): """ :type S: str :rtype: str """ n = len(S) buckets = [0]*26 max_rep = 0 for c in S: offset = ord(c)-ord(‘a‘) buckets[offset] += 1 if buckets[offset] > max_rep: max_rep = buckets[offset] if max_rep > (n+1)/2: return "" result = [None]*n even = 0 odd = 1 for i in xrange(26): if buckets[i] < n/2+1: while buckets[i] > 0 and odd < n: result[odd] = chr(ord(‘a‘)+i) buckets[i] -= 1 odd += 2 while buckets[i] > 0: result[even] = chr(ord(‘a‘)+i) buckets[i] -= 1 even += 2 return "".join(result)
优先队列法:
class Solution(object): def reorganizeString(self, S): """ :type S: str :rtype: str """ n = len(S) pq = [[0, chr(ord(‘a‘)+i)] for i in xrange(26)] max_rep = 0 for c in S: offset = ord(c)-ord(‘a‘) pq[offset][0] -= 1 if pq[offset][0] < max_rep: max_rep = pq[offset][0] if abs(max_rep) > (n+1)/2: return "" heapq.heapify(pq) result = [] while len(pq) >= 2: count1, c1 = heapq.heappop(pq) count2, c2 = heapq.heappop(pq) if count1 == 0 or count2 == 0: heapq.heappush(pq, [count1, c1]) heapq.heappush(pq, [count2, c2]) break result.extend([c1, c2]) count1 += 1 count2 += 1 if count1 != 0: heapq.heappush(pq, [count1, c1]) if count2 != 0: heapq.heappush(pq, [count2, c2]) if len(pq): count, c = heapq.heappop(pq) if count != 0: result.append(c) return "".join(result)
class Solution(object): def findLongestWord(self, s, d): """ :type s: str :type d: List[str] :rtype: str """ def isSubsequence(s, item): s_len = len(s) item_len = len(item) i = j = 0 while i < s_len and j < item_len and (s_len-i) >= (item_len - j): if s[i] == item[j]: j += 1 i += 1 return j == item_len def compare_func(x, y): if len(x) > len(y) or (len(x) == len(y) and x <= y): return 1 return -1 d.sort(cmp=compare_func, reverse=True) for item in d: if isSubsequence(s, item): return item return ""
class Solution(object): def carFleet(self, target, position, speed): """ :type target: int :type position: List[int] :type speed: List[int] :rtype: int """ n = len(position) if n == 0: return 0 car_arr = [[position[i], speed[i]] for i in xrange(n)] car_arr.sort(key=lambda x: x[0]) car_group_num = 1 if n > 0 else 0 for i in xrange(n-2, -1, -1): if float(target-car_arr[i][0])/car_arr[i][1] <= float(target-car_arr[i+1][0])/car_arr[i+1][1]: car_arr[i][0], car_arr[i][1] = car_arr[i+1][0], car_arr[i+1][1] else: car_group_num += 1 return car_group_num
class Solution(object): def pancakeSort(self, A): """ :type A: List[int] :rtype: List[int] """ n = len(A) index = sorted(range(n), key=lambda i: A[i]) def swap_value(A, index, end): start = 0 while start < end: index[A[start]-1], index[A[end]-1] = index[A[end]-1], index[A[start]-1] A[start], A[end] = A[end], A[start] start += 1 end -= 1 swap_flag = n-1 convert = [] while swap_flag > 0: num_index = index[swap_flag] if num_index != swap_flag: if num_index != 0: convert.append(num_index+1) swap_value(A, index, num_index) convert.append(swap_flag+1) swap_value(A, index, swap_flag) swap_flag -= 1 return convert
直接计算位置的提交代码:
class Solution(object): def pancakeSort(self, A): """ :type A: List[int] :rtype: List[int] """ n = len(A) index_pos = sorted(range(1, n+1), key=lambda i: -A[i-1]) convert = [] for i in index_pos[:-1]: for c in convert: if c >= i: i = c - i + 1 if i < n: convert.extend([i, n]) n -= 1 return convert
class Solution(object): def diagonalSort(self, mat): """ :type mat: List[List[int]] :rtype: List[List[int]] """ row = len(mat) if row == 0: return mat col = len(mat[0]) diags = [] for c in xrange(col-1, -1, -1): tmp_row = 0 tmp_col = c tmp = [] while tmp_row < row and tmp_col < col: tmp.append(mat[tmp_row][tmp_col]) tmp_row += 1 tmp_col += 1 tmp.sort() tmp_row = 0 tmp_col = c i = 0 while tmp_row < row and tmp_col < col: mat[tmp_row][tmp_col] = tmp[i] i += 1 tmp_row += 1 tmp_col += 1 for c in xrange(1, row): tmp_row = c tmp_col = 0 tmp = [] while tmp_row < row and tmp_col < col: tmp.append(mat[tmp_row][tmp_col]) tmp_row += 1 tmp_col += 1 tmp.sort() tmp_row = c tmp_col = 0 i = 0 while tmp_row < row and tmp_col < col: mat[tmp_row][tmp_col] = tmp[i] i += 1 tmp_row += 1 tmp_col += 1 return mat
class Solution(object): def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ n = len(nums) if n == 0: return 0 S = [0]*n S[0] = nums[0] for i in xrange(1, n): S[i] = S[i-1] + nums[i] return self.mergeSort(S, 0, n-1, lower, upper, 0) def mergeSort(self, S, start, end, lower, upper, count): if start == end: count = count+1 if S[start] >= lower and S[end] <= upper else count return count mid = (start + end) / 2 count = self.mergeSort(S, start, mid, lower, upper, count) count = self.mergeSort(S, mid+1, end, lower, upper, count) left = start low = up = mid + 1 # cal count while left <= mid and (low <= end or up <= end): while low <= end and S[low] - S[left] < lower: low += 1 up = low if low > up else up if low <= end and S[low]-S[left] <= upper: while up <= end and S[up] - S[left] <= upper: up += 1 count += (up - low) left += 1 # sort list tmp = [] i = start j = mid + 1 while i <= mid or j <= end: if i > mid: tmp.extend(S[j:end+1]) break elif j > end: tmp.extend(S[i:mid+1]) break else: if S[i] <= S[j]: tmp.append(S[i]) i += 1 else: tmp.append(S[j]) j += 1 for i in xrange(len(tmp)): S[start+i] = tmp[i] return count
二分法:
class Solution(object): def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ n = len(nums) if n == 0: return 0 S = [0]*(n+1) for i in xrange(1, n+1): S[i] = S[i-1] + nums[i-1] sort_list = [] count = 0 for tmp_sum in S[::-1]: lower_s = lower + tmp_sum up_s = upper + tmp_sum l = bisect.bisect_left(sort_list, lower_s) r = bisect.bisect_right(sort_list, up_s) count += (r-l) bisect.insort(sort_list, tmp_sum) return count
class Solution(object): def wiggleSort(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ n = len(nums) if n <= 1: return nums mid_index = (n-1)/2 start = 0 end = n-1 while True: tmp = nums[start] org_start = start org_end = end while start < end: while start < end and nums[end] >= tmp: end -= 1 if start < end: nums[start] = nums[end] start += 1 while start < end and nums[start] <= tmp: start += 1 if start < end: nums[end] = nums[start] end -= 1 nums[start] = tmp if start == mid_index: break elif start < mid_index: start = start + 1 end = org_end else: end = start - 1 start = org_start # 3-way-partation mid_value = nums[mid_index] i = j = 0 k = n-1 while j < k: if nums[j] > mid_value: nums[j], nums[k] = nums[k], nums[j] k -= 1 elif nums[j] < mid_value: nums[i], nums[j] = nums[j], nums[i] i += 1 j += 1 else: j += 1 left_part = nums[:mid_index+1] right_part = nums[mid_index+1:] for i in xrange(len(left_part)): nums[2*i] = left_part[-i-1] for i in xrange(len(right_part)): nums[1+2*i] = right_part[-i-1] return nums
标签:odi 给定一个整数数组 忽略 理解 str 偶数 交集 origin 程序
原文地址:https://www.cnblogs.com/luohaixian/p/12301972.html