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

数组理论知识

1 数组内存空间的地址是连续的,删除或者增添元素的时候,要移动其他元素
2 数组的元素是不能删除的,只能覆盖

LeetCode704二分查找

题目链接:https://leetcode.cn/problems/binary-search/

写法一:左闭右闭

class Solution {
    public static int search(int[] nums, int target) {
    
        int i = 0;
        int j = nums.length-1;

        while (i <= j){
            int index = (i + j) >> 1;
            if (nums[index] > target){
                j = index - 1;
                continue;
            }
            if (nums[index] < target){
                i = index + 1;
                continue;
            }
            if (nums[index] == target ){
                return index;
            }
        }
        return  -1;
    }
}

写法2:左闭右开

class Solution {
    public static int search(int[] nums, int target) {
    
        int i = 0;
        int j = nums.length-1;

        while (i < j){
            int index = (i + j) >> 1;
            if (nums[index] > target){
                j = index;
                continue;
            }
            if (nums[index] < target){
                i = index + 1;
                continue;
            }
            if (nums[index] == target ){
                return index;
            }
        }
        return  -1;
    }
}

Leetcode 27 移除元素

题目链接:https://leetcode.cn/problems/remove-element/

暴力破解

时间复杂度:O(n^2)
空间复杂度:O(1)

双指针(快慢指针法)

public class Solution {
    public static int removeElement(int[] nums, int val) {
        int slow = 0;
        for (int fast = 0;fast < nums.length;fast++){
            if (nums[fast] != val){
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值