LeeCode刷题 | 704. 二分查找、27. 移除元素

Leetcode704-二分查找

(方法一)左闭右闭区间

Java:

class Solution {
    public int search(int[] nums, int target) {
        // 避免当 target 小于nums[0] nums[nums.length - 1]时多次循环运算
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < target)
                left = mid + 1;
            else if (nums[mid] > target)
                right = mid - 1;
        }
        return -1;
    }
}

Golang:

func search(nums []int, target int) int {
    left := 0
    right := len(nums) - 1
    for left <= right{
        mid := (right - left)/2 + left
        num := nums[mid]
        if num == target{
            return mid
        }else if num > target{
            right = mid - 1
        }else{
            left = mid + 1
        }
    }
    return -1
}

(方法二)左闭右开区间

Java:

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

27-移除元素

(方法一)快慢指针

Java:

class Solution {
    public int removeElement(int[] nums, int val) {
        // 快慢指针
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;
    }
}

Golang:

func removeElement(nums []int, val int) int {
    slowIndex := 0
    for fastIndex := 0;fastIndex < len(nums);fastIndex ++{
        if nums[fastIndex] != val{
            nums[slowIndex] = nums[fastIndex]
            slowIndex ++
        }
    }
    return slowIndex
}

(方法二)双向指针

Java:

//相向双指针法
class Solution {
    public int removeElement(int[] nums, int val) {
        int left = 0;
        int right = nums.length - 1;
        while(right >= 0 && nums[right] == val) right--; //将right移到从右数第一个值不为val的位置
        while(left <= right) {
            if(nums[left] == val) { //left位置的元素需要移除
                //将right位置的元素移到left(覆盖),right位置移除
                nums[left] = nums[right];
                right--;
            }
            left++;
            while(right >= 0 && nums[right] == val) right--;
        }
        return left;
    }
}

你可能感兴趣的:(算法,leetcode,数据结构,java,golang)