标签:
Implement int sqrt(int x)
.
Compute and return the square root of x.
解法:二分搜索
时间复杂度O(logN), 空间复杂度O(1)
1 class Solution { 2 public: 3 int sqrt(int x) { 4 int low = 1; 5 int high = x / 2; 6 int mid, ans; 7 8 if (x < 2) return x; 9 10 while (low <= high) { 11 mid = low + (high - low) / 2; 12 if (mid <= x / mid) { 13 low = mid + 1; 14 ans = mid; 15 } else { 16 high = mid - 1; 17 } 18 } 19 20 return ans; 21 } 22 };
标签:
原文地址:http://www.cnblogs.com/vincently/p/4299988.html