欢迎来到我的博客,我是Sting,一名天津大学研究生码农,与你持续交流分享
- Leetcode 35题 搜索插入位置 链接: [link](https://leetcode-cn.com/problems/search-insert-position/).
- Leetcode 69题 x 的平方根[link](https://leetcode-cn.com/problems/sqrtx/).
- Leetcode 367题 有效的完全平方数[link](https://leetcode-cn.com/problems/valid-perfect-square/).
- Leetcode 704题 二分查找[link](https://leetcode-cn.com/problems/binary-search/).
Leetcode 35题 搜索插入位置 链接: link.
题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
我是这么想的
这道题目比较基础,用二分查找的基础思路,按部就班的做就好。
首先定义左边界和右边界,在while循环中定义中间值的索引,并增加判断条件,若中间的数值恰好等于目标值,则返回中间数值的索引,若中间值大于目标值,则更新右边界,并设置为中间值索引减一,若中间值小于目标值,则更新左边界,并设置为中间值索引加一。退出循环时,左边界等于右边界,返回左右边界均可。
我的代码
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length -1;
while(left <= right){
int mid = left + (right - left)/2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid -1;
}else if(nums[mid] < target){
left = mid + 1;
}
}
return left;
}
}
Leetcode 69题 x 的平方根link.
题目描述
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。由于返回类型是整数,结果只保留整数部分 ,小数部分将被舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
我是这么想的
这道题目首先排除x 为0和x 为1的情况,接下来使用二分查找的思路,如上题,左右边界和中间值索引,比较中间值的平方和目标值x的大小,不断更新左右边界,直到找到需要寻找的答案即可。
我的代码
class Solution {
public int mySqrt(int x) {
if(x==0){
return 0;
}
if(x==1){
return 1;
}
int left = 0;
int right = x;
int mid = 0;
while(left<=right){
mid = left + (right - left)/2;
if(mid == x/mid){
return mid;
}else if(mid > x/mid){
right = mid -1;
}else if(mid < x/mid){
left = mid + 1;
}
}
return right;
}
}
Leetcode 367题 有效的完全平方数link.
题目描述
给定一个正整数 num, 编写一个函数,如果 num 是一个完全平方数,则返回 true ,否则返回 false 。
我是这么想的
这道题目里面,一般来讲,除了正整数为1的情况,其余正整数的算术平方根都小于其一半,所以首先排除 num 为1的情况,接下来使用二分查找的思路,定义左边界为0,右边界为 (num /2)和中间值索引,比较中间值的平方和 num 的大小,在二分查找的思路上找到答案。
我的代码
class Solution {
public boolean isPerfectSquare(int num) {
if(num == 1) return true;
long left = 0, right = num / 2;
while (left <= right) {
long mid = left + (right - left) / 2;
long res = mid * mid;
if (res > num) {
right = mid - 1;
} else if (res < num){
left = mid + 1;
} else {
return true;
}
}
return false;
}
}
Leetcode 704题 二分查找link.
题目描述
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
我是这么想的
这道题目使用二分查找的思路,定义一下左右边界,判断中间值和目标值的大小关系,寻找题目所求。
我的代码
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (right - left) / 2 + left;
int num = nums[mid];
if (num == target) {
return mid;
} else if (num > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}