中级农民
- 积分
- 115
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-12-7
- 最后登录
- 1970-1-1
|
补昨天的记录 8月9 日 刷题第九天 打卡第九天
昨天做了2道题, 题目还是做少了,加油!
1. Find an element in a sorted matrix;
Assumption:
the matrix is sorted.
the matrix not containing any duplicates elements.
the matrix is not null.
Analysis && High level:
This a sorted matrix, so it could be transferred from a matrix into an array, so I can use the binary search to find the element by using O(logN) time complexity;
Details:
I would use two pointers, which is the left and right pointers
The left pointer represents the smallest element in the unprocessed range, the right pointer represents the largest element in the unprocessed range. During the process, cut half of the range and use the left half as the target range to process, never rule out the right answer.
And left starts from the leftMost and right Starts from the rightMost, two pointers comes toward each other and the terminal condition is the gap of the two pointers is less than 2;
During the process, I will use a mid pointer which is the middle pointer of the search range, compare its element towards its target, if it is smaller than the target, move the left pointer; else if it is larger than the target, move the right pointer, else return the position;
Outside of the loop, I would check the left and right position separately and find if any of them is equals to target, return the position (if applicable) or return {-1, -1}.
2. Find K closest elements in the array
-check the corner case including the array is not null or the array is empty and the k is smaller or equals to 0
-then find the largestSmallerEqual
-then use a while loop to traverse the array in a comparing order;
|
|