title: 【每日一题】LeetCode 633. 平方数之和
tags:

  • 每日一题
  • leetcode
  • acwing
    abbrlink: 3d4cbd1d
    date: 2021-04-29 18:26:08

LeetCode 633.平方数之和

思路

优化掉一层循环即可

C++代码

  1. class Solution {
  2. public:
  3. bool judgeSquareSum(int c) {
  4. for(int a=0; (long long)a*a<=c;a++)
  5. {
  6. int t=c-a*a;
  7. int r=sqrt(t);
  8. if(r*r==t)
  9. return true;
  10. }
  11. return false;
  12. }
  13. };

AcWing 1221.四平方和

思路

哈希+二分,预处理以后按照条件输出即可,这里也需要优化掉两层循环

C++代码

  1. #include <iostream>
  2. #include <cstring>
  3. #include <algorithm>
  4. using namespace std;
  5. const int N = 5000010;
  6. int n;
  7. int C[N], D[N];
  8. int main()
  9. {
  10. scanf("%d", &n);
  11. memset(C, -1, sizeof(C));
  12. for(int c=0;c*c<=n;c++)
  13. for(int d=c;d*d+c*c<=n;d++)
  14. {
  15. int s=c*c+d*d;
  16. if(C[s]==-1)
  17. C[s]=c, D[s]=d;
  18. }
  19. for(int a=0;a*a<=n;a++)
  20. for(int b=a; a*a+b*b<=n;b++)
  21. {
  22. int s=n-a*a-b*b;
  23. if(C[s]!=-1)
  24. {
  25. printf("%d %d %d %d\n", a, b, C[s], D[s]);
  26. return 0;
  27. }
  28. }
  29. return 0;
  30. }