代码随想录DAY1-704二分查找 27移除元素 数组

代码随想录DAY1-704二分查找 27移除元素 数组

以前也断断续续刷过一些题,但没有系统记录打卡的习惯,从现在开始吧

这两道题都是关于数组知识的,详细的概念参考了卡哥的介绍:https://programmercarl.com/%E6%95%B0%E7%BB%84%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html#%E6%95%B0%E7%BB%84%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80

704 二分查找

二分查找就是是利用数组的有序性,每轮缩窄一半的查找区间。关键是理解缩窄区间的含义,左闭右闭。时间复杂度 O(logN)。
通过首尾指针,计算数组长度,折半向下取整后比对和target的大小,判断是左还是右。

Java解法

java.

// An highlighted block
class Solution {
    public int search(int[] nums, int target) {
        int i = 0, j = nums.length - 1;
        while (i <= j) {
            int m = (i + j) / 2;
            if (nums[m] < target) i = m + 1;
            else if (nums[m] > target) j = m - 1;
            else return m;
        }
        return -1;
    }
}

Python解法

Python.

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        i, j = 0, len(nums) - 1
        while i <= j:
            m = (i + j) // 2
            if nums[m] < target: i = m + 1
            elif nums[m] > target: j = m - 1
            else: return m
        return -1

27 移除元素

该题我的思路是遍历元素,然后和val元素进行对比。主要思路是双指针,java中是快慢指针。
前半段存储不等于val的元素,后半段存储等于val的元素

Java解法

java.

class Solution {
    public int removeElement(int[] nums, int val) {
        int n = nums.length;

        if (n < 1) {
            return n;
        }

        int slow = 0; 
        int fast = 0;
        while (fast < n) {
            if (nums[fast] == val) {
                fast++;
                continue;
            }
            nums[slow++] = nums[fast++];
        }

        return slow;
    }
}

另一种解法,遍历元素与val对比,如果当前元素和val相同那么跳过,否则将其放到idx的位置,最终的数组即为答案。

java.

class Solution {
    public int removeElement(int[] nums, int val) {
        int idx = 0;
        for (int x : nums) {
            if (x != val) nums[idx++] = x;
        }
        return idx;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值