15 三数之和

今天药忘吃喽~ 2024-02-19 15:55 114阅读 0赞

超时的代码,我不咋会优化,请大神指教

  1. class Solution {
  2. public static List<List<Integer>> threeSum(int[] nums) {
  3. List<List<Integer>> numsR = new ArrayList<List<Integer>>();
  4. List<Integer> intList;
  5. int zeroSign = 0;
  6. for(int i = 0 ;i < nums.length ;i++) {
  7. for(int j = 0 ; j < i ; j ++) {
  8. for(int k = 0 ; k < j ; k++ ) {
  9. if(nums[i]+nums[j]+nums[k]==0) {
  10. intList = new ArrayList<Integer>();
  11. intList.add(nums[i]);
  12. intList.add(nums[j]);
  13. intList.add(nums[k]);
  14. if(nums[i]==0&&nums[j]==0&&nums[k]==0&&zeroSign==0) {
  15. numsR.add(intList);
  16. zeroSign+=1;
  17. continue;
  18. }
  19. if(hasEqual(numsR, intList)) continue;
  20. else {
  21. numsR.add(intList);
  22. }
  23. }
  24. }
  25. }
  26. }
  27. return numsR;
  28. }
  29. public static boolean hasEqual(List<List<Integer>> basic , List<Integer> list) {
  30. Iterator<List<Integer>> listinfo = basic.iterator();
  31. List<Integer> buffer ;
  32. while(listinfo.hasNext()) {
  33. buffer = listinfo.next();
  34. if(buffer.containsAll(list)) return true;
  35. }
  36. return false;
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读

    相关 15.之和

    [题目][Link 1] 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足

    相关 15. 之和

    链接:https://leetcode-cn.com/problems/3sum 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,

    相关 15.之和

    题目描述 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元