代码随想录day01 | 数组理论基础、Leetcode 704 二分查找、Leetcode 27 移除元素

代码随想录day01 | 数组理论基础、Leetcode 704 二分查找、Leetcode 27 移除元素

704 二分查找

左闭右开

//左闭右开
class Solution {
    public int search(int[] nums, int target) {
        int begin = 0;
        int end = nums.length;
        int mid = begin + (end - begin) / 2;
        System.out.println("mid = " + mid);
        while (begin < mid) {
            if (nums[mid] > target) {
                end = mid;
                mid = begin + (end - begin) / 2;
            } else if (nums[mid] < target) {
                begin = mid;
                mid = begin + (end - begin) / 2;
            } else {
                return mid;
            }
            System.out.println("begin = " + begin);
            System.out.println("mid = " + mid);
            System.out.println("end = " + end);
        }
        //排除首次begin==end情况
        if (nums[mid] == target) {
            return mid;
        }
        return -1;
    }
}

左闭右闭

//左闭右闭
class Solution {
    public int search(int[] nums, int target) {
        int begin = 0;
        int end = nums.length - 1;
        int mid = begin + (end - begin) / 2;
        //此时右边界end-1
        while (begin < end - 1) {
            if (nums[mid] > target) {
                end = mid;
                mid = begin + (end - begin) / 2;
            } else if (nums[mid] < target) {
                begin = mid;
                mid = begin + (end - begin) / 2;
            } else {
                return mid;
            }
            System.out.println("begin = " + begin);
            System.out.println("mid = " + mid);
            System.out.println("end = " + end);
        }
        if (nums[begin] == target) {
            return begin;
        } else if (nums[end] == target) {
            return end;
        }
        return -1;
    }
}

27 移除元素

// 27. 移除元素
//双指针
class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        int j = nums.length - 1;

        for (; i <= j; i++) {
            while (nums[i] == val) {
                swap(nums, i, j);
                j--;
                //分两种情况讨论当前值nums[i]是否为val
                if (i >= j) {
                    if (nums[i] == val) {
                        return i;
                    } else {
//                        nums = Arrays.copyOf(nums, i + 1);
                        return i + 1;
                    }
                }
            }
        }
//        nums = Arrays.copyOf(nums, i + 1);
        return i;
    }

    public void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值