633. Sum of Square Numbers(平方和)(leetcode)
阿新 • • 發佈:2019-02-22
時間復雜度 ron html lis src hide 平方根 you HERE
題目:
Given a non-negative integer c
, your task is to decide whether there‘re two integers a
and b
such that a2 + b2 = c.
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False
方法一:雙指針
雙指針主要用於遍歷數組,兩個指針指向不同的元素。從而協調完成任務。
之前我讓j=c;沒有考慮到平方根還是欠妥當。導致運行時間過長。
時間復雜度:o(n) 運行時間:6ms 占用內存:37mb
方法二:數學方法
時間復雜度:o(n) 運行時間:13385 ms 占用內存:37.1mb
一般不建議使用直觀感受想出的方法,太耗時。
時間復雜度:o(nlog(n) 運行時間:8 ms 占用內存:37.1mb
方法三:二分法查找
二分查找也稱為折半查找,每次都能將查找區間減半,這種折半特性的算法時間復雜度為 O(logN)。
時間復雜度:O(√ ̄c 運行時間:53ms 占用內存:37mb
633. Sum of Square Numbers(平方和)(leetcode)