Leetcode 第一天

704.二分法
https://leetcode.com/problems/binary-search/description/?envType=list&envId=pgm5myyh

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

需注意以下

1.right的界线位置

如使用

int right = nums.length-1;
会导致nums少遍历几个元素

2.nums.length==1需另外处理

因left及right会相等,无法进入while迴圈处理

27.移除元素
https://leetcode.com/problems/remove-element/description/?envType=list&envId=pgm5myyh

class Solution {    public 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];                slow++;            }        }        return slow;    }}

解题概念:

使用快慢指针,当快指针位置不等于val,便让nums[slow]=快指针位置,以及slow++。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章