代码随想录刷题第一天|LeetCode704 二分查找、LeetCode34、Leetcode27移除元素

1、LeetCode704 二分查找

题目链接: 704. 二分查找

分为左闭右闭[left,right],左闭右开[left,right)两种方式。

//左闭右闭
class Solution {
public:
    int search(vector& nums, int target) {
        int left = 0;
        int right = nums.size() - 1;       //   nums.size() - 1
        while(left<=right)                 //    <=
        {
            int middle = (left + right) / 2;
            if(nums[middle]>target)
            {
                right = middle - 1;        // right = middle - 1
            }
            else if(nums[middle]
//左闭右开
class Solution {
public:
    int search(vector& nums, int target) {
        int left = 0;
        int right = nums.size() ;       //   nums.size()
        while(left> 1 );
            if(nums[middle]>target)
            {
                right = middle;        // right = middle 
            }
            else if(nums[middle]

2、LeetCode34 在排序数组中查找元素的第一个和最后一个位置

题目链接:34. 查找元素第一个和最后一个位置

这道题有点难度,二刷时要再认真研究一下。

思想:寻找左右边界点,右边界点随左指针的增加而变化,左边界点随右指针的减少而变化,分为三种情况:

1. target 在数组范围的右边或者左边,例如数组{3, 4, 5},target为2或者数组{3, 4, 5},target为6,左边界点或右边界点不更新;

2. target 在数组范围中,数组中不存在target,例如数组{3,6,7},target为5,此时应该返回{-1, -1},左右边界点更新后差值不大于1;

3. target 在数组范围中,且数组中存在target,例如数组{3,6,7},target为6,此时应该返回{1, 1},左右边界点更新后差值大于1,返回 [leftBorder+1, rightBorder-1];

class Solution{
public:
    vector searchRange(vector& nums, int target) {
        int LeftBorder = getLeftBorder(nums, target);
        int rightBorder = getRightBorder(nums, target);

        if (LeftBorder == -2 || rightBorder == -2)
        {
            return {-1,-1};
        }
        if (rightBorder - LeftBorder > 1) 
        {
            return { LeftBorder + 1, rightBorder - 1 };
        }
        return { -1, -1 };
	}

private:
	int getRightBorder(vector& nums, int target) {
		int left = 0;
		int right = nums.size() - 1;
		int rightBorder = -2;
		while (left <= right)
		{
			int middle = (left + right) / 2;
			if (nums[middle] > target)
			{
				right = middle - 1;
			}
			else
			{
				left = middle + 1;
				rightBorder = left;
			}
		}
		return rightBorder;
	}

	int getLeftBorder(vector& nums, int target) {
		int left = 0;
		int right = nums.size() - 1;
		int LeftBorder = -2;
		while (left <= right)
		{
			int middle = (left + right) / 2;
			if (nums[middle] >= target)
			{
				right = middle - 1;
				LeftBorder = right;
			}
			else
			{
				left = middle + 1;
			}
		}
		return LeftBorder;
	}


};

3、LeetCode27 移除元素

题目链接:27、移除元素

暴力解法:

class Solution {
public:
    int removeElement(vector& nums, int val) {
        int size = nums.size();
        for(int i = 0; i < size;i++)
        {
            if (nums[i] == val)
            {
                for (int j = i+1; j

双指针法(快慢指针法):

class Solution {
public:
    int removeElement(vector& nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex

你可能感兴趣的:(算法,数据结构)