文章目录题目描述思路 & 代码更新版 题目描述 本质:找满足 k * k <= x 的最大 k 思路 & 代码 二分,对满足 k * k <= x 的最大 k进行查找。注意极端数据,用 long暴力法先来一个 class Solution {public int mySqrt(int x) {int ans = -1;for(int i = 0; i <= x; i++){if((long)i * i <= x){ans = i;}else{break;}}return ans;} } 二分 class Solution {public int mySqrt(int x) {int ans = -1;int left = 0, right = x;// 二分法:查找最大的,满足 mid * mid <= x 的值为answhile(left <= right){int mid = (left + right) / 2;// long:极端数据if((long)mid * mid <= x){ans = mid;left = mid + 1;}else{right = mid - 1;}}return ans;} } 更新版 只能说这道题真的挺恶心的…本质还是二分,小心边界。 class Solution {public int mySqrt(int x) {if(x == 1) {return 1;}int left = 0, right = x;while(left + 1 < right) {int mid = (left + right) / 2;if(x / mid < mid) {right = mid;}else {left = mid;}}return left;} }