题目链接

思路

不知道是不是用kotlin提交的人少呀,内存和时间又击败了100%的用户,哈哈哈。思路也是借鉴的网上的。

先排序,排好后遍历。怎么遍历呢,若一个数小于等于0,则使用双指针法对数组位于这个数前面的部分扫描一遍,找到符合的三元组加入结果;大于0直接结束就可以了,因为这个数之后都是正数,不会存在三个数加起来等于0。

为了防止重复,我使用了一个数据类来存储三元组,覆写了equal和hashcode方法,用一个set存储结果集。

代码

  1. data class Three(
  2. val x: Int,
  3. val y: Int,
  4. val z: Int
  5. ){
  6. override fun equals(other: Any?): Boolean {
  7. if (this === other) return true
  8. if (javaClass != other?.javaClass) return false
  9. other as Three
  10. if (x != other.x) return false
  11. if (y != other.y) return false
  12. if (z != other.z) return false
  13. return true
  14. }
  15. override fun hashCode(): Int {
  16. var result = x
  17. result = 31 * result + y
  18. result = 31 * result + z
  19. return result
  20. }
  21. }
  22. class Solution {
  23. fun threeSum(nums: IntArray): List<List<Int>> {
  24. val result = mutableListOf<List<Int>>()
  25. val resultSet = mutableSetOf<Three>()
  26. nums.sort()
  27. for (i in 0 until nums.size - 2) {
  28. if (nums[i] > 0) break
  29. var pLeft = i + 1
  30. var pRight = nums.size - 1
  31. while (pLeft < pRight) {
  32. val sum = nums[i] + nums[pLeft] + nums[pRight]
  33. if (sum == 0) {
  34. val three = Three(nums[i], nums[pLeft], nums[pRight])
  35. if (!resultSet.contains(three)) {
  36. result.add(listOf(nums[i], nums[pLeft], nums[pRight]))
  37. resultSet.add(three)
  38. }
  39. pRight--
  40. pLeft++
  41. }else if (sum > 0) {
  42. pRight--
  43. }else{
  44. pLeft++
  45. }
  46. }
  47. }
  48. return result
  49. }
  50. }