栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

每周leetcode - leetcode704/34/88/1

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

每周leetcode - leetcode704/34/88/1

文章目录
        • leetcode-704 二分查找
        • leetcode-34 在排序数组中查找元素的第一个和最后一个位置
        • leetcode-88 合并两个有序数组
        • leetcode-1 两数之和

leetcode-704 二分查找

方法1 :

public class Solution {
    public int search1(int[] nums, int target) {
        int start = 0;
        int end = nums.length-1;
        while (start<=end){
            int mid = start + (end-start)/2;
            // 先判断有没有找到
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]>target){
                end= mid-1;
            }else{
                start = mid+1;
            }
        }
        //如果最后没找到,start和end会指向同一个值,如果找到最后才找到,start和end和mid会指向target
        return -1;
    }
}

方法2 :

public int search(int[] nums, int target) {
    int start = 0;
    int end = nums.length-1;
    while (start+1=nums[mid]){
            start= mid;
        }else{
            end= mid;
        }
    }
    //循环结束后,start和end会指向两个值,永远不会指向同一个
    if(nums[start]==target) return start;
    if(nums[end]==target) return end;
    return -1;
}
leetcode-34 在排序数组中查找元素的第一个和最后一个位置
public class Solution {
    public  int[] searchRange(int[] nums, int target) {
        if(nums==null || nums.length==0) return new int[]{-1,-1};
        List result = new ArrayList<>();
        int first = findFirst( nums, target);
        int last = findLast( nums, target);
        return new int[]{first,last};
    }

    private int findLast(int[] nums, int target) {
        int start = 0;
        int end = nums.length-1;
        while (start+1 
leetcode-88 合并两个有序数组 
class Solution {
    public  void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m-1;
        int j = n-1;
        int k = m+n-1;
        while (i>=0 && j>=0){
            if(nums1[i]>=nums2[j]){
                nums1[k--] = nums1[i--];
            }else{
                nums1[k--] = nums2[j--];
            }
        }
        while (j>=0){
            nums1[k--] = nums2[j--];
        }
        while (i>=0){
            nums1[k--] = nums1[i--];
        }
    }
}
leetcode-1 两数之和

方法1:暴力法,时间复杂度O(n^2)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length==0 || nums==null) return null;
        for(int i=0;i 

方法2:用空间换时间,时间复杂度O(n)。空间复杂度O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length==0 || nums==null) return null;
        Map map = new HashMap<>();
        for(int i=0;i
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/305895.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号