标签:bsp extend range bool lint array pen www problem
二分法的时间复杂度:logN
算法面试复杂度:
1.O(1) 不出现
2.o(logN) 二分法
3.o(n^1/2) 分解质因数
4.o(n) 高频
5.o(nlogn) 一般排序
6.O(N^2)数组 枚举 动态规划
7.O(N^3) 数组 枚举 动态规划
8.O(2^n) 与组合有关搜索
9.O(n!) 与排列有关的搜索
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/
1 class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 int[] res = new int[2]; 4 res[0] =-1; 5 res[1] = -1; 6 if(nums==null || nums.length==0){ 7 return res; 8 } 9 10 11 int start =0; 12 int end = nums.length-1; 13 while(start +1 <end){ 14 int mid = start +(end-start)/2; 15 if(nums[mid]==target){ 16 end = mid; 17 }else if(nums[mid]>target){ 18 end = mid; 19 }else{ 20 start = mid; 21 } 22 } 23 if(nums[end]==target){ 24 res[0] = end; 25 } 26 if(nums[start]==target){ 27 res[0] = start; 28 } 29 30 start =0; 31 end = nums.length-1; 32 33 while(start +1 <end){ 34 int mid = start +(end-start)/2; 35 if(nums[mid]==target){ 36 start = mid; 37 }else if(nums[mid]>target){ 38 end = mid; 39 }else{ 40 start = mid; 41 } 42 } 43 if(nums[start]==target){ 44 res[1] = start; 45 } 46 if(nums[end]==target){ 47 res[1] = end; 48 } 49 50 return res; 51 } 52 }
https://leetcode.com/problems/first-bad-version/submissions/
1 /* The isBadVersion API is defined in the parent class VersionControl. 2 boolean isBadVersion(int version); */ 3 4 public class Solution extends VersionControl { 5 public int firstBadVersion(int n) { 6 if(n<1){ 7 return 0; 8 } 9 10 int start =1; 11 int end = n; 12 13 while(start + 1< end){ 14 int mid = start +(end-start)/2; 15 if(isBadVersion(mid)){ 16 end = mid; 17 }else{ 18 start = mid; 19 } 20 } 21 22 if(isBadVersion(start)){ 23 return start; 24 } 25 if(isBadVersion(end)){ 26 return end; 27 } 28 return 0; 29 } 30 }
https://www.lintcode.com/problem/search-in-a-big-sorted-array/description
1 public class Solution { 2 /* 3 * @param reader: An instance of ArrayReader. 4 * @param target: An integer 5 * @return: An integer which is the first index of target. 6 */ 7 public int searchBigSortedArray(ArrayReader reader, int target) { 8 // write your code here 9 if(reader.get(0)==target){ 10 return 0; 11 } 12 int start = 1; 13 while(reader.get(start)<target){ 14 start = start*2; 15 } 16 17 int end = start; 18 start =1; 19 while(start+1<end){ 20 int mid = start +(end-start)/2; 21 if(reader.get(mid)==target){ 22 end = mid; 23 }else if(reader.get(mid)>target){ 24 end = mid; 25 }else{ 26 start = mid; 27 } 28 } 29 30 if(reader.get(start)==target){ 31 return start; 32 } 33 if(reader.get(end) == target){ 34 return end; 35 } 36 return -1; 37 } 38 }
标签:bsp extend range bool lint array pen www problem
原文地址:https://www.cnblogs.com/lizzyluvcoding/p/10353210.html