【LeetCode】初级算法:排序和搜索

1. 合并两个有序数组

用时:5ms

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i=0,j=0,temp1,temp2;
        while(j<n&&i<(m+j)){
            // 找到插入点
            if(nums1[i]<=nums2[j]){
                ++i;
                continue;
            }
            // 插入nums2的元素
            temp1=nums1[i];
            nums1[i++]=nums2[j++];
            // 将插入点后的元素右移
            for(int s=i;s<(m+j);++s){
                temp2=nums1[s];
                nums1[s]=temp1;
                temp1=temp2;
            }
        }
        while(j<n){
            nums1[i++]=nums2[j++];
        }
    }
}

2. 第一个错误的版本

用时:17ms

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int s=1,e=n,c=(n+1)/2;
        while(s!=e){
            if(isBadVersion(c)){
                e=c;
            }else{
                s=c+1;
            }
            // 两个大int相加会导致溢出
            c=(int)(s/2.0+e/2.0);
        }
        return c;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值