solution.json 2.7 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
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
{
  "type": "code_options",
  "author": "csdn.net",
  "source": "solution.md",
  "exercise_id": "85e648677c4a4d2f91b670310348f77a",
  "keywords": "数组,双指针,排序",
  "title": "最接近的三数之和",
  "desc": [
    {
      "content": "\n<p>给定一个包括&nbsp;<em>n</em> 个整数的数组&nbsp;<code>nums</code><em>&nbsp;</em>和 一个目标值&nbsp;<code>target</code>。找出&nbsp;<code>nums</code><em>&nbsp;</em>中的三个整数,使得它们的和与&nbsp;<code>target</code>&nbsp;最接近。返回这三个数的和。假定每组输入只存在唯一答案。</p><p>&nbsp;</p><p><strong>示例:</strong></p><pre><strong>输入:</strong>nums = [-1,2,1,-4], target = 1<strong><br />输出:</strong>2<strong><br />解释:</strong>与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。</pre><p>&nbsp;</p><p><strong>提示:</strong></p><ul>\t<li><code>3 &lt;= nums.length &lt;= 10^3</code></li>\t<li><code>-10^3&nbsp;&lt;= nums[i]&nbsp;&lt;= 10^3</code></li>\t<li><code>-10^4&nbsp;&lt;= target&nbsp;&lt;= 10^4</code></li></ul>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "cpp"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "cpp"
      }
    ],
    [
      {
        "content": "",
        "language": "cpp"
      }
    ],
    [
      {
        "content": "",
        "language": "cpp"
      }
    ]
  ],
  "template": {
    "content": "#include <cstdlib>\nclass Solution\n{\npublic:\n\tint threeSumClosest(vector<int> &nums, int target)\n\t{\n\t\tsort(nums.begin(), nums.end());\n\t\tint cur, left, right;\n\t\tcur = 0;\n\t\tint closest = nums[0] + nums[1] + nums[2];\n\t\twhile (cur < nums.size() - 2)\n\t\t{\n\t\t\tleft = cur + 1;\n\t\t\tright = nums.size() - 1;\n\t\t\tint n;\n\t\t\twhile (left < right)\n\t\t\t{\n\t\t\t\tn = nums[cur] + nums[left] + nums[right];\n\t\t\t\tif (abs(target - n) < abs(target - closest))\n\t\t\t\t{\n\t\t\t\t\tclosest = n;\n\t\t\t\t}\n\t\t\t\tif (n == target)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (n > target)\n\t\t\t\t{\n\t\t\t\t\tint t = right - 1;\n\t\t\t\t\twhile (t > left && nums[t] == nums[right])\n\t\t\t\t\t\tt--;\n\t\t\t\t\tright = t;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint t = left + 1;\n\t\t\t\t\twhile (t < right && nums[t] == nums[left])\n\t\t\t\t\t\tt++;\n\t\t\t\t\tleft = t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tint t = cur + 1;\n\t\t\twhile (t < nums.size() && nums[t] == nums[cur])\n\t\t\t\tt++;\n\t\t\tcur = t;\n\t\t}\n\t\treturn closest;\n\t}\n};",
    "language": "cpp"
  },
  "node_id": "dailycode-c32c095cff5545278e9e9e51bb3cdbe1",
  "license": "csdn.net",
  "created_at": 1637894158,
  "topic_link": "https://bbs.csdn.net/topics/600471102"
}