代码随想录算法训练营第一天 | LeetCode704二分查找、LeetCode27 移除元素

代码随想录算法训练营第一天 | LeetCode704二分查找、LeetCode27 移除元素

2022-12-28

时长:大约2小时

704. Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Constraints:

  • 1 <= nums.length <= 10<sup>4</sup>
  • -10<sup>4</sup> < nums[i], target < 10<sup>4</sup>
  • All the integers in nums are unique .
  • nums is sorted in ascending order.

解题思路:

理解题意:

  • 数组元素已排序好
  • 每个元素互不相同
  • 基于上述两个条件考虑可以使用二分搜索

实现细节:

  • 左闭右闭:

    while(right >= left) { //闭区间,因此right == left 有意义
        mid = left + (right - left) / 2; // 防止溢出
        if(nums[mid] > target) {
            right = mid - 1;   
        }
        else if(nums[mid] < target) {
            left = mid + 1;
        }
    }
    
  • 左闭右开:

    int left = 0, right = nums.size();
    int mid = left + (right - left) / 2;
    while(right > left) { //开区间,因此right == left 无意义 
        if(nums[mid] > target) {
            right = mid;
        }
        else if(nums[mid] < target) {
            left = mid + 1;
        }
    }
    

需要注意的要点:

理清开闭区间关系

27. Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k* after placing the final result in the first k slots of *nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
    assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted .

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

解题思路:

理解题意:

  • 对于指定的元素进行去除,但由于数组的连续存储,没办法单独去掉一个元素,只能将其覆盖;

思路一:

采用暴力法,每遇到一个目标元素,后续的元素向前移动1

思路二:

采用类似排序的方法,把目标元素一个个移动到数组的最末尾

思路三

采用快慢指针的方法,通过慢指针对要保留的元素重新构筑索引,通过快指针遍历所有元素,跳过目标元素

需要注意的要点:

对于不同的思路,要注意返回值,即除去目标元素后的数组大小怎么返回。

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        if (nums.size() == 0) {
            return 0;
        }



        // carl 双指针
        int slowIndex = 0;
        for(int fastIndex = 0; fastIndex < nums.size(); ++ fastIndex) {
            if (nums[fastIndex] != val) {
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        return slowIndex;
  
	// carl 纯暴力法
        int size = nums.size();
        for(int i = 0; i < size; ++ i) {
            if (nums[i] == val) {
                for(int j = i + 1; j < size; ++ j) {
                    nums[j-1] = nums[j];
                }
                i --;
                size --;
            }
        }  
        return size;

        // 暴力法
        int size = nums.size();
        int cnt = 0;

        for(int i = 0; i < size; ++ i) {
            if (nums[i] == val) {
                for(int j = i + 1; j < size - cnt; ++ j) {
                    nums[j-1] = nums[j];
                }
                cnt ++;
            }
        }

        return size - cnt;

        // 类似排序的双指针
        int begin = 0, end = nums.size() - 1;
  
        while(end >= begin) {

            while (nums[end] == val && end > begin) {
                end --;
            }
            while (nums[begin] != val && begin < end) {
                begin ++;
            }

            if (begin < end) {
                nums[begin] = nums[end];
                nums[end] = val;
                end --;
                begin ++;
            }
            else if(begin == end) {
                if (nums[begin] != val) {
                    break;
                }
                else {
                    end --;
                    break;
                }
            }
            else {
                break;
            }
        }
        return end + 1;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值