File size: 1,981 Bytes
ce5cd7e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
{
"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
}
|