两指针(5)
来源:互联网 发布:淘宝直播的运营怎么做 编辑:程序博客网 时间:2024/05/18 18:02
原题:
/** * Created by gouthamvidyapradhan on 29/03/2017. * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. * <p> * Note: The solution set must not contain duplicate triplets. * <p> * For example, given array S = [-1, 0, 1, 2, -1, -4], * <p> * A solution set is: * [ * [-1, 0, 1], * [-1, -1, 2] * ] */
答案:
public class ThreeSum { /** * Main method * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int[] nums = {-1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4}; System.out.println(new ThreeSum().threeSum(nums)); } public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums.length < 3) return result; Arrays.sort(nums); for (int i = 0, l = nums.length; i < l - 2; i++) { if (i == 0 || nums[i] != nums[i - 1]) { int j = i + 1, k = l - 1; while (k > j) { if (j != i + 1 && nums[j] == nums[j - 1]) { j++; continue; } int sum = nums[i] + nums[j] + nums[k]; if (sum == 0) { result.add(Arrays.asList(nums[i], nums[j], nums[k])); k--; j++; } else if (sum > 0) k--; else j++; } } } return result; }}
阅读全文
0 0
- 两指针(5)
- 两指针(1)
- 两指针(2)
- 两指针(3)
- 两指针(4)
- 两指针(6)
- 两指针(7)
- 比较两数大小(指针)
- 精致树叶鼠标指针(两款)
- 第十七周项目2-5-比较两字符串,返回值同strcmp()(指针做形参)
- 比较两数大小(指向函数的指针变量)
- 比较两数大小(指针函数版)
- 第十七周项目3-两种排序(指针做形参)
- 用指针比较两数的大小(2)
- 智能指针的两种实现(引用计数)
- 邻接表的两种实现(双向+非指针)
- 切分 字符串指针数组(如环境变量) 的两种方法, 数组下标 和 指针
- 指针、数组、字符串(二)两句话分清数组和指针
- Python中strip和split的使用
- Java多线程编程-(13)-从volatile和synchronized的底层实现原理看Java虚拟机对锁优化所做的努力
- Win10下安装Cisco VPN Client终极解决方法
- springmvc工作原理
- css js 实现图片动态切换
- 两指针(5)
- MongoDB:16-MongoDB-索引数组字段和索引子文档字段
- laoshidaima(用户管理商品)
- 排座位 要安排:3个A国人,3个B国人,3个C国人坐成一排。 要求不能使连续的3个人是同一个国籍。 求所有不同方案的总数?
- 两指针(6)
- 乐观锁和悲观锁的区别(最全面的分析)
- 两指针(7)
- 浅谈从源代码文件到二进制可执行文件的过程
- 寻找最大公因数(欧几里得算法)--C语言描述