【备战字节面试】算法特训-二分查找

149 阅读1分钟

简单粗暴,记录备战过程,持续更新

二分查找

适用场景

实战

实战1 4. 寻找两个正序数组的中位数

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null ){
			return 0;
	}
	int len1 = nums1.length, len2 = nums2.length, sum = len1 + len2;
	List<Integer> list = new ArrayList<Integer>();
	for (int i = 0, j = 0; i < len1 || j < len2;) {
		if (i >= len1) {
			list.add(nums2[j++]);
		} else if (j >= len2) {
			list.add(nums1[i++]);
		} else if (nums1[i] <= nums2[j]) {
			list.add(nums1[i++]);
		} else {
			list.add(nums2[j++]);
		}
	}
	// 偶数
	if (sum % 2 == 0) {
		return (list.get(sum / 2) + list.get(sum / 2 - 1)) / 2.0;
	} else {
		return list.get(sum / 2);
	}
    }
}

实战2 392. 判断子序列

class Solution {
    public boolean isSubsequence(String s, String t) {
        if(s.length() == 0){
            return true;
        }
        if( t.length() == 0){
            return false;
        }
        int sIdx = 0;
        int tIdx = 0;
        while(tIdx < t.length()){
            if(s.charAt(sIdx) == t.charAt(tIdx)){
                sIdx++;
            }
            if(sIdx == s.length()){
                return true;
            }
            tIdx++;
        }
        return false;
    }
}

实战3 34. 在排序数组中查找元素的第一个和最后一个位置

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] ans = new int[]{-1,-1};
        if(nums.length == 0){
            return ans;
        }
        // 二分查找
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            int privot = (left + right) /2;
            if(nums[privot] < target){
                left = privot + 1;
            } 
            if(nums[privot] > target){
                right = privot - 1;
            } 
            if(nums[privot] == target){
                int tmpLeft = privot;
                int tmpRight = privot;
                // 左边
                while(tmpLeft >= left && nums[tmpLeft] == target){
                    tmpLeft--;
                }
                // 右边
                while(tmpRight <= right && nums[tmpRight] == target){
                    tmpRight++;
                }
                ans[0] = tmpLeft + 1;
                ans[1] = tmpRight - 1;
                break;
            }
        } 
        return ans;
    }
}