LeetCode OJ-35-Search Insert Position
来源:互联网 发布:瑞士军刀软件 编辑:程序博客网 时间:2024/06/05 18:48
题目:
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
大意:
给定一个排序数组,和一个指定的值,如果找到这个值,返回这个值位置,如果没有找到,返回这个值在数组中的插入位置。假设数组中没有重复的元素。
思路:
使用二分查找,时间复杂度为O(log(n))。
代码:
public class Solution { public int searchInsert(int[] nums, int target) { if(nums == null) { return -1; } int i = 0; int j = nums.length - 1; int mid; while(i <= j) { mid = (i + j) / 2; if(nums[mid] == target) { return mid; } else if(nums[mid] < target) { i = mid + 1; } else { j = mid - 1; } } return i; }}
1 0
- LeetCode OJ-35-Search Insert Position
- LeetCode OJ:Search Insert Position
- LeetCode OJ - Search Insert Position
- [LeetCode OJ]Search Insert Position
- LeetCode OJ Search Insert Position
- LeetCode OJ - Search Insert Position
- LeetCode OJ 系列之35 Search Insert Position --Python
- 【LeetCode OJ 035】Search Insert Position
- <LeetCode OJ> 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 35 Search Insert Position
- Leetcode 35 Search Insert Position
- Leetcode[35]-Search Insert Position
- 关于HashMap的工作原理
- 【论文笔记】Deep Learning Face Representation from Predicting 10,000 Classes
- 最近这一年
- 64. Minimum Path Sum
- jQuery plugin: Autocomplete 参数及实例
- LeetCode OJ-35-Search Insert Position
- count, sum和 if,case when
- css背景渐变兼容性问题解决
- 很好用的Java web分页工具类
- caffe: Ubuntu16.04 + cuda8.0 + cudnn8.0 + opencv3.1.0 + python2.7 + matlab2014b + blas(mkl)
- Hibernate从入门到精通(二)Hibernate实例演示
- 【论文笔记】Recover Canonical-View Faces in the Wild with Deep Neural Network
- 《运维之下》——第九章:网络成长之路
- vmware FAQ