算法练习LeetCode初级算法之排序和搜索
-
合并两个有序数组
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
System.arraycopy(nums2, 0, nums1, m, n);
Arrays.sort(nums1);
}
}
-
第一个错误的版本
-
递归解法:自己突然来了灵感写的,哈哈哈,递归真的很神奇!
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
class Solution extends VersionControl {
public int firstBadVersion(int n) {
return helper(0, n);
}
private int helper(int l,int r) {
if (l<r) {
int m=l+(r-l)/2;
if (isBadVersion(m)) {
return helper(l, m);
}else {
return helper(m+1, r);
}
}
return l;
}
}
-
二分法解法:
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int l=1;
int r=n;
while(l<r){
int m=l+((r-l)/2);
if(isBadVersion(m)){
r=m;
}else{
l=m+1;
}
}
return l;
}
}
-
很慢的解法:
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int i=1;
while(i<=n){
if(isBadVersion(i)){
break;
}
i++;
}
return i;
}
}