classSolution{publicintsearch(int[] nums,int target){int n = nums.length;int left =0;int right = n -1;int res =-1;while(left <= right){int mid =(left +right)>>1;//这里分类,看的是旋转之后,前半段和后半段的比例if(nums[left]<= nums[mid]){//这里是看哪里是顺序段,因为二分搜索只适用于顺序区间if(nums[left]<= target && nums[mid]>= target){
right = mid -1;}else{
left = mid +1;}}else{if(nums[mid]<= target && nums[right]>= target){
left = mid +1;}else{
right = mid -1;}}if(nums[mid]== target){
res = mid;}}return res;}}
1.2.2. 三数之和类问题
基础版,三数之和 时间复杂度:O(
n
2
n^2
n2)
classSolution{publicList<List<Integer>>threeSum(int[] nums){//排序数组Arrays.sort(nums);//初始化结果集合以及数组长度int n = nums.length;List<List<Integer>> res =newArrayList<>();for(int i =0; i < n -2; i++){int x = nums[i];//去重if(i >0&& nums[i]== nums[i -1]){continue;}//优化减枝if(x + nums[i +1]+ nums[i +2]>0){break;}if(x + nums[n -1]+ nums[n -2]<0){continue;}int j = i +1;int k = n -1;while(j < k){int sum = x + nums[j]+ nums[k];if(sum >0){
k--;}elseif(sum <0){
j++;}elseif(sum ==0){
res.add(List.of(x, nums[j], nums[k]));//优化减枝for(j +=1; j < k && nums[j]== nums[j -1]; j++){continue;}for(k -=1; j < k && nums[k]== nums[k +1]; k--){continue;}}}}return res;}}
平方根问题
X 的平方根
有效的完全平方根
两道题代码几乎一致,只写第二题
classSolution{publicbooleanisPerfectSquare(int num){long i =1;long j = num /2;while(i < j){long mid = i +((j - i +1)>>1);if(mid > num / mid){
j = mid -1;}elseif(mid == num / mid){
i = mid;}else{
i = mid;}}if(i * i == num){returntrue;}returnfalse;}}