Swift solution - Binary Search, Set, Two Pointers


  • 2
    class Solution {
        func judgeSquareSum_BinarySearch(_ c: Int) -> Bool {
            let sqrtC = Int(sqrt(Double(c)))
            
            for i in 0...sqrtC {
                var left = i
                var right = sqrtC
                let middle = (i + sqrtC) / 2
                while left <= right {
                    if i * i + middle * middle == c {
                        return true
                    } else if i * i + middle * middle < c {
                        left = middle + 1
                    } else {
                        right = middle - 1
                    }
                }
            }
            
            return false
        }
        
        func judgeSquareSum_TwoPointer(_ c: Int) -> Bool {
            var left = 0
            var right = Int(sqrt(Double(c)))
            
            while left <= right {
                let sum = left * left + right * right
                if sum == c {
                    return true
                } else if sum < c {
                    left += 1
                } else {
                    right -= 1
                }
            }
            
            return false
        }
        
        func judgeSquareSum_Set(_ c: Int) -> Bool {
            var set = Set<Int>()
            
            for i in 0...Int(sqrt(Double(c))) {
                let i2 = i * i
                set.insert(i2)
                if set.contains(c - i2) {
                    return true
                }
            }
            
            return false
        }
    }
    

  • 0
    T

    Nice work!!!!!!!!!!!!!!!!!!!!!


  • 0
    A

    What is the time complexity for this solution?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.