使用二分搜索查找给定数的立方根的Java程序
给定一个非负数,使用二进制搜索方法找到一个数的立方根。
例子 :
Input: x = 27
Output: 3
Explanation: The cube root of 16 is 4.
Input: x = 120
Output: 4
Explanation: The cube root of 120 lies in between
4 and 5 so floor of the cube root is 4.
天真的方法:
- 检查每个元素的立方体直到 n 并存储答案直到立方体小于或等于 n
Java
// Java Program to Find the cube root
// of given number using Naive approach
import java.io.*;
class GFG {
static int cuberoot(int n)
{
int ans = 0;
for (int i = 1; i <= n; ++i) {
// checking every number cube
if (i * i * i <= n) {
ans = i;
}
}
return ans;
}
public static void main(String[] args)
{
// Number
int number = 27;
// Checking number
int cuberoot = cuberoot(number);
System.out.println(cuberoot);
}
}
Java
// Java Program to Find the cube root
// of given number using Binary Search
import java.io.*;
import java.util.*;
class GFG {
// Function to find cuberoot
static int cuberoot(int number)
{
// Lower bound
int left = 1;
// Upper bound
int right = number;
int ans = 0;
while (left <= right) {
// Finding the mid value
int mid = left + (right - left) / 2;
// Checking the mid value
if (mid * mid * mid == number) {
return mid;
}
// Shift the lower bound
if (mid * mid * mid < number) {
left = mid + 1;
ans = mid;
}
// Shift the upper bound
else {
right = mid - 1;
}
}
// Return the ans
return ans;
}
public static void main(String[] args)
{
int number = 215;
System.out.println(cuberoot(number));
}
}
输出
3
复杂:
SpaceComplexity: O(1)
TimeComplexity: O(n)
高效方法(二分搜索):
二分搜索使用分而治之的方法,使得复杂度为 O(log n)。
算法:
- 初始化 left=0 和 right =n
- 计算mid=left+(right-left)/2
- 如果 mid*mid*mid 等于数字返回 mid
- 如果 mid*mid*mid 小于数字,则将 mid 存储在 ans 中并增加 left=mid+1
- 如果 mid*mid*mid 大于数字并减少 right=mid-1
- 返回答案
执行:
Java
// Java Program to Find the cube root
// of given number using Binary Search
import java.io.*;
import java.util.*;
class GFG {
// Function to find cuberoot
static int cuberoot(int number)
{
// Lower bound
int left = 1;
// Upper bound
int right = number;
int ans = 0;
while (left <= right) {
// Finding the mid value
int mid = left + (right - left) / 2;
// Checking the mid value
if (mid * mid * mid == number) {
return mid;
}
// Shift the lower bound
if (mid * mid * mid < number) {
left = mid + 1;
ans = mid;
}
// Shift the upper bound
else {
right = mid - 1;
}
}
// Return the ans
return ans;
}
public static void main(String[] args)
{
int number = 215;
System.out.println(cuberoot(number));
}
}
输出
5
复杂:
SpaceComplexity: O(1)
TimeComplexity: O(log n)