1.搜索一个范围
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
class Solution {
public:
vector searchRange(vector& nums, int target) {
vector res(2, -1);
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else right = mid;
}
if (nums[right] != target) return res;
res[0] = right;
right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) left = mid + 1;
else right= mid;
}
res[1] = left - 1;
return res;
}
};
class Solution {
public:
vector searchRange(vector a, int x) {
int n = a.size() - 1;
vector res(2, -1);
if (n < 1) return res;
int left = 0, right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (x > a[mid])
{
left = mid + 1;
}
else
{
right = mid;
}
}
res[0] = left;
right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (x >= a[mid])
{
left = mid + 1;
}
else
{
right = mid;
}
}
res[1] = left -1;
return res;
}
};
2.Clone Graph 无向图的复制
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use #
as a separator for each node, and ,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
0
. Connect node 0
to both nodes 1
and 2
.1
. Connect node 1
to node 2
.2
. Connect node 2
to node 2
(itself), thus forming a self-cycle.Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
这道无向图的复制问题和之前的拷贝链表有些类似,那道题的难点是如何处理每个节点的随机指针,这道题目的难点在于如何处理每个节点的neighbors,由于在深度拷贝每一个节点后,还要将其所有neighbors放到一个vector中,而如何避免重复拷贝呢?这道题好就好在所有节点值不同,所以我们可以使用哈希表来对应节点值和新生成的节点。对于图的遍历的两大基本方法是深度优先搜索DFS和广度优先搜索BFS,此题的两种解法可参见网友爱做饭的小莹子的博客,这里我们使用深度优先搜索DFS来解答此题,代码如下:
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map umap;
return clone(node, umap);
}
UndirectedGraphNode *clone(UndirectedGraphNode *node, unordered_map &umap) {
if (!node) return node;
if (umap.count(node->label)) return umap[node->label];
UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
umap[node->label] = newNode;
for (int i = 0; i < node->neighbors.size(); ++i) {
(newNode->neighbors).push_back(clone(node->neighbors[i], umap));
}
return newNode;
}
};
3.LRU cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and put
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
这道题让我们实现一个LRU缓存器,LRU是Least Recently Used的简写,就是最近最少使用的意思。那么这个缓存器主要有两个成员函数,get和put,其中get函数是通过输入key来获得value,如果成功获得后,这对(key, value)升至缓存器中最常用的位置(顶部),如果key不存在,则返回-1。而put函数是插入一对新的(key, value),如果原缓存器中有该key,则需要先删除掉原有的,将新的插入到缓存器的顶部。如果不存在,则直接插入到顶部。若加入新的值后缓存器超过了容量,则需要删掉一个最不常用的值,也就是底部的值。具体实现时我们需要三个私有变量,cap, l和m,其中cap是缓存器的容量大小,l是保存缓存器内容的列表,m是HashMap,保存关键值key和缓存器各项的迭代器之间映射,方便我们以O(1)的时间内找到目标项。
然后我们再来看get和put如何实现,get相对简单些,我们在m中查找给定的key,若不存在直接返回-1。如果存在则将此项移到顶部,这里我们使用C++ STL中的函数splice,专门移动链表中的一个或若干个结点到某个特定的位置,这里我们就只移动key对应的迭代器到列表的开头,然后返回value。这里再解释一下为啥HashMap不用更新,因为HashMap的建立的是关键值key和缓存列表中的迭代器之间的映射,get函数是查询函数,如果关键值key不在HashMap,那么不需要更新。如果在,我们需要更新的是该key-value对在缓存列表中的位置,而HashMap中还是这个key跟键值对儿的迭代器之间的映射,并不需要更新什么。
对于put,我们也是现在m中查找给定的key,如果存在就删掉原有项,并在顶部插入新来项,然后判断是否溢出,若溢出则删掉底部项(最不常用项)。代码如下:
class LRUCache{
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
auto it = m.find(key);
if (it == m.end()) return -1;
l.splice(l.begin(), l, it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = m.find(key);
if (it != m.end()) l.erase(it->second);
l.push_front(make_pair(key, value));
m[key] = l.begin();
if (m.size() > cap) {
int k = l.rbegin()->first;
l.pop_back();
m.erase(k);
}
}
private:
int cap;
list> l;
unordered_map>::iterator> m;
};