leetcode_704原题链接
class Solution {
public int search(int[] nums, int target) {
int high = nums.length-1;
int low = 0;
int value = 0;
while(high>=low) {
value = (high+low)/2;
if (nums[value]==target) {
return value;
}
else if (nums[value]>target) {
high = value-1;
}
else {
low = value+1;
}
}
return -1;
}
}
leetcode_35原题链接
class Solution {
public int searchInsert(int[] nums, int target) {
if (nums.length==0) {
return 0;
}
int l = 0;
int r = nums.length-1;
int mid;
while (l<r) {
mid = l+(r-l)/2;
if (nums[mid]==target) {
return mid;
}
else if (nums[mid]>target) {
r = mid;
}
else {
l = mid+1;
}
}
if (nums[l]>target) {
return l;
}
else if(nums[l]<target){
return l+1;
}
else {
return l;
}
}
}
leetcode_162寻找峰值
class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 0) {
return -1;
}
int l = 0;
int right = nums.length-1;
int mid ;
while (l<right) {
mid = l+(right-l)/2;
if (nums[mid]>nums[mid+1]) {
right = mid;
}
else {
l = mid+1;
}
}
return l ;
}
}
leetcode_74搜索二维矩阵
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int l = 0;
int r = m*n-1;
int mid;
while (l<r) {
mid = l+(r-l)/2;
if (matrix[mid/n][mid%n]==target) {
return true;
}
else if (matrix[mid/n][mid%n]>target) {
r = mid;
}
else {
l = mid+1;
}
}
if (matrix[l/n][l%n]==target) {
return true;
}
return false;
}
}