[leetcode-查找]--35. Search Insert Position
2017-02-08 16:01
531 查看
Question 35. Search Insert Position
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
中文: 给定一个有序数组和目标值target。如果target在数组中就返回索引,如果不在就返回插入位置的索引。
这题一看就比较简单,直接一轮遍历就可以解决:
测试案例:
输出:
本文完整源码github:
https://github.com/leetcode-hust/leetcode/blob/master/louyuting/src/leetcode/Question35.java
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
中文: 给定一个有序数组和目标值target。如果target在数组中就返回索引,如果不在就返回插入位置的索引。
这题一看就比较简单,直接一轮遍历就可以解决:
public static int searchInsert(int[] nums, int target) { for(int i=0; i<nums.length; i++){ //找到就直接返回index if(nums[i] == target ){ return i; } if(nums[i] < target && i< (nums.length-1) && nums[i+1] > target){ return i+1; } if(nums[i] < target && i==(nums.length-1)){ return nums.length; } } //当nums[0]都比target大时 return 0; }
测试案例:
public static void main(String[] args) { int[] arr = {0, 1, 2, 3, 4, 7, 8, 9, 12, 22, 65}; System.out.print( Question35.searchInsert(arr, 44)) ; }
输出:
10
本文完整源码github:
https://github.com/leetcode-hust/leetcode/blob/master/louyuting/src/leetcode/Question35.java
相关文章推荐
- 【LeetCode35】【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(查找插入位置)
- LeetCode 35 Search Insert Position 二叉查找相关(一)
- LeetCode:35. Search Insert Position
- LeetCode | Search Insert Position(查找插入位置)
- Search Insert Position_Leetcode_35
- Leetcode-35 Search Insert Position
- leetcode: 35. Search Insert Position
- LeetCode-35-Search Insert Position(搜素并插入指定位置)
- LeetCode-35-Search Insert Position(二分法)-Medium
- LeetCode之路——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