633. Sum of Square Numbers(平方和)(leetcode)

题目:

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(√ ̄clog(c)).    运行时间:53ms   占用内存:37mb


苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
原文地址:https://www.cnblogs.com/shaer/p/10418403.html