中级农民
- 积分
- 106
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-8-18
- 最后登录
- 1970-1-1
|
9/26 Wed Searching and Sorting
347. Top K Frequent Elements
做法: bucket Sorting
• Step1: use hashMap to count the frequency for each element
• Step2: create a list array as buckets. For Map's each key, get its frequency, insert into the buckets[frequency]
• Step 3: from buckets back to front, get k elements as most freqent element (找到一个buckets[i] 要先检查它是不是null,不是null才能寄到result list里面)
• 注意⚠️:list[] buckets = new list[n+1] //注意list要建立n + 1的长度,表示frequency最大是n,所有的数都一样
215. Kth Largest Element in an Array 找到数组中第k大的element
不难,但有多种方法
• Method1: sort the entire array and retrieve the n-k th element
• Time complexity O(nlogk) + space O(1) Java uses Quicksort algorithm which has O(n log n) average complexity and is performed in-place, no extra space is needed.
• Method2: use priorityQueue with fixed size k to store elements, then peek the first element is the k the largest element in the array
• Time complexity: O(nlogk) + space O(k) n个element,每次插入需要logK时间
Search for a Range
给一组递增的数组,找等于target数的一组index区间
分析:找到区间,就是用来找到等于target的第一个index和等于target的最后一个index。先用bianry search 来找到Starting index,end index 其实就是target的下一个元素的index - 1
做法: 写一个binary search 的helper函数,用来找到等于target的index。在主函数中先得到left bound再得到helper(nums, target + 1) - 1作为right bound
253. Meeting Rooms II 和merge Interval 很相似
做法: 将start time 和 end time 进行分离分别存在int array 中进行排序。设一个endIdx从0开始的variable。进行for loop,如果start[i] < end[endIdx] 那么count++,否则就endIdx ++
240. Search a 2D Matrix II
We can rule out one row or one column each time, the time complexity is O(m+n).
Binary search , row = 0开始col = matrix[0].length - 1开始, 在while loop中查看matrix[row][col] 与target的大小关系
280. Wiggle Sort vs 324. Wiggle Sort II
280不难 in-place sort 即可。 324需要点小技巧
153 Find Minimum in Rotated Sorted Array (操作index)
Use index as search space. 不同的是这里是rotated sorted array, 那么用一个target = nums[n]来存一下,因为是rotated,所以小于target 才算做是small number。用binary search,如果中间的值小于target,end = mid, 说明在最小值还应该在mid的左边,让end = mid
142. Linked List Cycle II && 287 Find the Duplicate Number
大致思路都是一样的,用快慢两个指针先来找到第一次会和的地方,再需要一个从头开始的指针,再同步走到相遇的地方,便是结果。当时!!两个的写法有差,因为一个是在数组上进行,一个是在linkedList上
【总结】
Binary Search--> figure out the "Search Space"
Two kinds of "Search Space"
• Index: generally used for sorted array
• Range: used for unsorted array
Binary Search: O(logn)题目说比O(n)更优的方法几乎只能是O(logn)
• 第一类:套模版
• 第二类:OOXX 即找到符合条件的第一个or最后一个
• 第三类:Half Half 即每次保留一半
|
|