Skip to content

Instantly share code, notes, and snippets.

@advpetc
Last active June 5, 2019 23:09
Show Gist options
  • Select an option

  • Save advpetc/9a5d4ede710a06611b63b64a06aa02dd to your computer and use it in GitHub Desktop.

Select an option

Save advpetc/9a5d4ede710a06611b63b64a06aa02dd to your computer and use it in GitHub Desktop.
Leetcode snippets
/* Binary search */
// find first element from the sorted list that is greater than certain number
// e.g. find 3 from [2, 4, 5, 6, 9], ans should be the index of element 4 (first greater than)
int find(vector<int>& nums, int target) {
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else right = mid;
}
return right;
}
// find last element from the sorted list that is less than certain number
// e.g. find 3 from [2, 4, 5, 6, 9], ans should be the index of element 2 (first greater than)
int find(vector<int>& nums, int target) {
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else right = mid;
}
return right - 1;
}
// Note: the only difference is the return value is right -> right - 1
/* LinkedList */
// note: 如果head在返回结果中变了,那么需要declare一个dummy
// swap 0 1 and 3 4
// 0(pre) 1(curr) 3(temp) 4(temp->next)
ListNode* temp = curr->next;
curr->next = temp->next; // delete 3: 0 1 4
temp->next = pre->next; // 0 4 1
pre->next = temp; // 0(pre) 3(temp) 4(temp->next) 1(curr)
pre = pre->next; // 0 3(pre, temp) 4(temp->next) 1(curr)
// cycle in linked list, where does it start?
// https://www.cnblogs.com/hiddenfox/p/3408931.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment