LeetCode【35】Search Insert Position
2017-12-04 13:14
344 查看
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
给你一个排好序的数组和一个target,如果数组中有一个和target相等的则返回该数的索引,没有则返回该插入地方的索引
思想:很典型的二分查找,根据中间值大小分成两个区间进行查找,比较简单的题目,直接上代码了解下就好了
Example 1:
Example 2:
Example 3:
Example 4:
You may assume no duplicates in the array.
给你一个排好序的数组和一个target,如果数组中有一个和target相等的则返回该数的索引,没有则返回该插入地方的索引
思想:很典型的二分查找,根据中间值大小分成两个区间进行查找,比较简单的题目,直接上代码了解下就好了
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
public static int Sip(int[] nums, int target) { if (nums == null || nums.length == 0) { return 0; } int l = 0; int r = nums.length - 1; while (l <= r) { int mid = (l + r) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) l = mid + 1; else r = mid - 1; } return l; } public static void main(String[] args) { int[] nums = new int[]{2, 3, 5, 7, 8}; int target = 4; System.out.println(Sip(nums, target)); }
相关文章推荐
- [LeetCode] 35.Search Insert Position
- [LeetCode] 35. Search Insert Position
- Leetcode35: Search Insert Position
- LeetCode 35 -Search Insert Position ( JAVA )
- 【LeetCode35】【Search Insert Position】二分法查找
- LeetCode 35: Search Insert Position
- LeetCode 35 — Search Insert Position(C++ Java Python)
- LeetCode Problem 35:Search Insert Position
- [Leetcode]_35 Search Insert Position
- leetcode-- 35. Search Insert Position
- LeetCode----- 35.Search Insert Position
- LeetCode-35-Search Insert Position(搜素并插入指定位置)
- LeetCode-35-Search Insert Position(二分法)-Medium
- LeetCode35 Search Insert Position
- LeetCode:35. Search Insert Position
- LeetCode 35:Search Insert Position
- leetcode[35]Search Insert Position
- LeetCode: 35. Search Insert Position
- leetcode35. Search Insert Position
- Leetcode-35 Search Insert Position