算法学习day01数组part01-704、27

复制代码
package SecondBrush.Array;

/**
 * 704. 二分查找
 */

public class BinarySearch_704 {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == nums[mid]) {
                return mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

}
复制代码
复制代码
package SecondBrush.Array;
/**
 * 27. 移除元素
 * 快慢指针
 * 这里可以使用暴力O(n^2),可以使用双指针 O(n)
 * */

public class RemoveElement_27 {
    public int remove_v(int []nums,int target){
        int len = nums.length;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target){
                for (int j = i+1; j < nums.length; j++) {
                    nums[j-1] = nums[j];
                    len--;
                    i--;
                }
            }
        }
        return len;
    }

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

}
复制代码

 

posted @   坤坤无敌  阅读(144)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示