二分查找
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.empty()) return -1;
return Bitsearch(nums, 0, nums.size()-1, target);
}
int Bitsearch(vector<int>& nums,int low, int high, int target){
if(low>high) return -1;
if(low == high){
if(nums[low]==target) return low;
else
return -1;
}
int mid = (high + low) / 2;
if(nums[mid] == target)
return mid;
else if(target>nums[mid])
return Bitsearch(nums, mid+1, high, target);
else
return Bitsearch(nums, low, mid-1, target);
}
};
两个栈实现队列
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
int ret = stack2.top();
stack2.pop();
while(!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
return ret;
}
private:
stack<int> stack1;
stack<int> stack2;
};
合并两个有序链表
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode *list = new ListNode(0);
ListNode *p = list;
while(pHead1 && pHead2){
if(pHead1->val < pHead2->val){
p->next = pHead1;
pHead1 = pHead1->next;
} else {
p->next = pHead2;
pHead2 = pHead2->next;
}
p = p->next;
}
if(pHead1){
p->next = pHead1;
} else{
p->next = pHead2;
}
return list->next;
}
};
判断链表中是否有环
struct ListNode{
int val;
struct ListNode *next;
ListNode(int x): val(x), next(NULL){ }
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL){
return false;
}
ListNode *fast = head;
ListNode *slow = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
链表中倒数最后k个结点
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
ListNode* first = pHead;
ListNode* second = pHead;
while(k--){
if(first != NULL){
first = first->next;
} else {
return second = NULL;
}
}
while(first != NULL){
first = first->next;
second = second->next;
}
return second;
}
};
单链表的排序
class Solution {
public:
ListNode* sortInList(ListNode* head) {
vector<int> nums;
ListNode *cur = head;
while(cur){
nums.push_back(cur->val);
cur = cur->next;
}
sort(nums.begin(), nums.end());
ListNode *dummy = new ListNode(0);
ListNode *res = new ListNode(0);
dummy->next = res;
for(auto i : nums){
res->next = new ListNode(i);
res = res->next;
}
res->next = nullptr;
return dummy->next->next;
}
};