LeetCode704
LeetCode27
LeetCode704 Binary Search
class Solution {
public:
int search(vector<int>& nums, int target) {
const auto it = ranges :: lower_bound(nums, target);
return (it == nums.cend() || *it != target) ? -1 : distance(nums.begin(), it);
}
};
- 时间复杂度:O(log n)
- 空间复杂度:O(1)
自己做的时候没有太考虑区间哪边开哪边闭的问题, 看了解题方案之后才有些理解。
LeetCode27 Remove Element
- 暴力解法
-
class Solution { public: int removeElement(vector<int>& nums, int val) { int size = nums.size(); for (int i = 0; i < size; i++){ //if the current number is the target to be removed if (nums[i] == val){ //then move the whole array one step forward for (int j = i + 1; j < size; j++){ nums[j - 1] = nums[j]; } i--; //i move one place alongside the array size--; //size of array -1 } } return size; } };
- 单指针(?)解法
-
class Solution { public: int removeElement(vector<int>& nums, int val) { int i = 0; for (const int num : nums) if (num != val) nums[i++] = num; return i; } };
- 双指针解法(快慢指针法)
-
class Solution { public: int removeElement(vector<int>& nums, int val) { int slowIndex = 0; for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++){ if (val != nums[fastIndex]){ nums[slowIndex++] = nums[fastIndex]; } } return slowIndex; } };