LeetCode - Square root of #69 x

Get into the habit of writing together! This is the 15th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

foreword

Our community will successively organize Gu Yi ( Netflix Growth Hacker, author of "The Way of the iOS Interview", ACE Professional Fitness Coach. )'s Swift algorithm problem solutions into a text version for everyone to learn and read.

We have updated 68 issues of LeetCode algorithm so far, and we will keep the update time and progress ( released at 9:00 am on Monday, Wednesday, and Friday ). There will be a big improvement.

If you don't accumulate a small step, you can't go a thousand miles; if you don't accumulate a small stream, you can't make a river. The Swift community accompanies you to move forward. If you have suggestions and comments, please leave a message at the end of the article, we will try our best to meet your needs.

Difficulty Level: Easy

1. Description

Given a non-negative integer x, compute and return xthe arithmetic square root of .

Since the return type is an integer, only the integer part of the result is retained, and the fractional part will be rounded .

Note: Any built-in exponential functions and operators such as pow(x, 0.5)or x ** 0.5.

2. Example

Example 1

输入:x = 4
输出:2
复制代码

Example 2

输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
复制代码

Restrictions:

  • 0 <= x <= 2^31 - 1

3. Answers

class Sqrtx {
    func mySqrt(_ x: Int) -> Int {
        guard x >= 0 else {
            return 0
        }
        
        var left = 0, right = x / 2 + 1
        
        while left <= right {
            let mid = (right - left) / 2 + left
            
            if mid * mid == x {
                return mid
            } else if mid * mid < x {
                left = mid + 1
            } else {
                right = mid - 1
            }
        }
        
        return right
    }
}
复制代码
  • Main idea: binary search, should x / 2 + 1start with , so its square is x + x ^ 2 / 4 + 1, it must be greater than x.
  • Time Complexity: O(logn)
  • Space Complexity: O(1)

Note: Please use (right-left)/2+left to get middle in case of integer overflow

Repository for the algorithm solution: LeetCode-Swift

Click to go to LeetCode practice

about us

We are jointly maintained by Swift enthusiasts. We will share the technical content centered on Swift combat, SwiftUI, and Swift foundation, and also organize and collect excellent learning materials.

Guess you like

Origin juejin.im/post/7087913552542957604