{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-10, 2, 8], [-7, -3, 10]]\n" ] } ], "source": [ "# Write a Python program to find the three elements that sum to zero from a set (array) of n real numbers.\n", "# Input\n", "# [-25, -10, -7, -3, 2, 4, 8, 10]\n", "# Output\n", "# [[-10, 2, 8], [-7, -3, 10]]\n", "\n", "class py_solution:\n", " def threeSum(self, nums):\n", " nums, result, i = sorted(nums), [], 0\n", " while i < len(nums) - 2:\n", " j, k = i + 1, len(nums) - 1\n", " while j < k:\n", " if nums[i] + nums[j] + nums[k] < 0:\n", " j += 1\n", " elif nums[i] + nums[j] + nums[k] > 0:\n", " k -= 1\n", " else:\n", " result.append([nums[i], nums[j], nums[k]])\n", " j, k = j + 1, k - 1\n", " while j < k and nums[j] == nums[j - 1]:\n", " j += 1\n", " while j < k and nums[k] == nums[k + 1]:\n", " k -= 1\n", " i += 1\n", " while i < len(nums) - 2 and nums[i] == nums[i - 1]:\n", " i += 1\n", " return result\n", "\n", "print(py_solution().threeSum([-25, -10, -7, -3, 2, 4, 8, 10]))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 2 }