【LeetCode】C# 35、Search Insert Position
2017-10-11 15:54
501 查看
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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
给定有序数组在其中找到目标值的位置或应该在的位置。
可以直接遍历找。
更好的是二分法找。
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
给定有序数组在其中找到目标值的位置或应该在的位置。
可以直接遍历找。
public class Solution { public int SearchInsert(int[] nums, int target) { for(int i=0;i<nums.Length;i++){ if(nums[i]>=target) return i; } return nums.Length; } }
更好的是二分法找。
public class Solution { public int SearchInsert(int[] nums, int target) { int l=0,r=nums.Length-1,m=0; while(l<=r){ m=(l+r)/2; if(nums[m]==target) return m; if(nums[m]>target) r=m-1; else l=m+1; } return l; } }
相关文章推荐
- 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 (C,C++,Java,Python)
- LeetCode 35 -Search Insert Position ( JAVA )
- LeetCode@Array_35_Search_Insert_Position
- Leetcode 35 Search Insert Position 二分查找(二分下标)
- leetcode 35: Search Insert Position
- The Solution to 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
- leetcode(35) - Search Insert Position
- 【LeetCode35】【Search Insert Position】二分法查找
- [LeetCode] 35.Search Insert Position
- LeetCode Problem 35:Search Insert Position
- LeetCode(35)--Search Insert Position
- leetcode - 35.Search Insert Position