{ "type": "code_options", "author": "csdn.net", "source": "solution.md", "exercise_id": "383deea124124fc3af6f677fa1cf9305", "keywords": "数组,二分查找", "title": "搜索插入位置", "desc": [ { "content": "\n
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0", "language": "markdown" } ], "answer": [ { "content": "", "language": "java" } ], "prepared": [ [ { "content": "", "language": "java" } ], [ { "content": "", "language": "java" } ], [ { "content": "", "language": "java" } ] ], "template": { "content": "class Solution {\n\tpublic int searchInsert(int[] nums, int target) {\n\t\tint left = 0, right = nums.length - 1;\n\t\tif (target < nums[left])\n\t\t\treturn 0;\n\t\tif (target > nums[right])\n\t\t\treturn nums.length;\n\t\twhile (left <= right) {\n\t\t\tint mid = (right - left) / 2 + left;\n\t\t\tif (target < nums[mid]) {\n\t\t\t\tright = mid - 1;\n\t\t\t} else if (target > nums[mid]) {\n\t\t\t\tleft = mid + 1;\n\t\t\t} else {\n\t\t\t\treturn mid;\n\t\t\t}\n\t\t}\n\t\treturn left;\n\t}\n}\n", "language": "java" }, "node_id": "dailycode-00a267eca7a84efdac846774beeb5766", "license": "csdn.net", "created_at": 1637894161, "topic_link": "https://bbs.csdn.net/topics/600470222" }
输出: 0