代码随想录算法训练营第一天| 704. 二分查找、27. 移除元素。

LeetCode704、Leetcode27

提示:基础题


前言

提示:这里可以添加本文要记录的大概内容:

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、数组

数组是存放在连续内存空间上的相同类型数据的集合。
需要注意:
1、数组下标都是从0开始的。
2、数组在内存物理地址中是连续的。

二、LeetCode刷题

1.LeetCode704 二分查找

代码如下(示例):

public class leetcode_704 {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid;

        while(left <= right){
            mid = (left + right) / 2;
            if(nums[mid] == target) return mid;
            if(nums[mid] > target) right = mid - 1;
            if(nums[mid] < target) left = mid + 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        leetcode_704 leetcode304 = new leetcode_704();
        int[] nums = new int[]{-1,0,3,5,9,12};
        System.out.println(leetcode304.search(nums, 9));
    }
}

2.LeetCode27 移除元素

代码如下(示例):

public class leetcode_27 {
    public int removeElement(int[] nums, int val) {
        int quick = 0;
        int slow = 0;
        int count = 0;
        while(quick < nums.length){
            if(nums[quick] != val){
                nums[slow] = nums[quick];
                quick++;
                slow++;
            }else if(nums[quick] == val){
                quick++;
                count++;
            }
        }
        return nums.length - count;
    }

    public static void main(String[] args) {
        leetcode_27 leetcode27 = new leetcode_27();
        int[] nums = {2};
        System.out.println(leetcode27.removeElement(nums, 3));
    }
}

总结

今天的这两道题比较简单。
写的时候有两个错误:
1、第一题,while(left <= right)没有加等号,当只有一个元素时,程序不能通过。
2、第二天,没写else if,直接写的if,执行第一个if以后quick++导致第二个if空指针异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值