当前位置: 首页 > news >正文

15. 三数之和

题目链接:15. 三数之和 - 力扣(LeetCode)

 

 

 

 

 

 

 

解析:

这题其实很简单,就是时间卡的太死,很离谱,确实是O(N^2)的方法,但循环里用个unorered_map都超时,

所以先排序,然后暴力就好了,暴力的基础上注意每层循环的值只取一次就ok,算不上优题,恶心题

class Solution {
public:vector<vector<int>> threeSum(vector<int>& nums) {std::unordered_map<int, int> vis;std::unordered_map<string, bool> ret_vis;set<string> h_set;for (int i = 0; i < nums.size(); i++) {vis[nums[i]] += 1;}sort(nums.begin(), nums.end());vector<vector<int>> ret;for (int i = 0; i < nums.size(); i++) {if (i > 0 && nums[i] == nums[i - 1]) continue;int a = nums[i];for (int j = i + 1; j < nums.size(); j++) {if (j > i + 1 && nums[j] == nums[j - 1]) continue;int b = nums[j];int c = 0 - a - b;if (vis[c] && c >= b) {if ((a == b || a == c) && vis[a] < 2 || b == c && vis[b] < 2) {continue;}if (a == b && a == c && vis[a] < 3) continue;int x = std::min(a, std::min(b, c));int z = std::max(a, std::max(b, c));int y = 0 - x - z;ret.push_back(vector<int> {a, b, c});}}}return ret;}
};

 


文章转载自:

http://www.tdrn.cn/news/2149/
http://www.tdrn.cn/news/2148/
http://www.tdrn.cn/news/2147/
http://www.kefakeji.com/news/737.html

相关文章:

  • 20250727
  • JTAG和SWD的简单了解
  • 齐治堡垒机资深工程师认证通关
  • 7.26每周总结
  • 7.19每周总结
  • day24
  • docker安装与镜像打包部署
  • AirSim在UE4中运行时显示第一人称捕获图像窗口
  • ArKTS:List 数组
  • 笔记:割空间、环空间、切边等价
  • 15Java基础之内部类
  • 第四天
  • 简单图论
  • minio 对象存储服务
  • 【计算几何】洛谷 P3256 [JLOI2013] 赛车
  • 旋转和扫掠
  • 投影和相交
  • 习题-笛卡尔积
  • 里革断罟匡君
  • java第二十七天
  • JAVA的学习
  • Luogu P8085 [COCI 2011/2012 #4] KRIPTOGRAM 题解 [ 蓝 ] [ KMP ] [ 哈希 ]
  • Burp Suite宏与会话处理实战:突破CSRF令牌防护
  • 2123D-Binary String Battle
  • 观后感
  • 第十三篇
  • [题解]P4116 Qtree3
  • 第二十五天
  • JAVA语言学习总结(第26天)
  • 初遇前端