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.
Example
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
Challenge
O(log(n)) time
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[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)) time
在做完6.合并排序数组II之后,系统推荐了一道相似题,就是这道搜索插入位置的题,这道题中也运用到了vector的知识,所以我查了一下基本用法,可以直接使用。例如,我可以运用库中已有函数插入vector<int> A; A.push_back(1);,这样就将整数1插入到了动态数组中。
这道题的挑战在于时间复杂度,因为给定的数组是有序的,所以要在循环中直接判断,这样可以减少循环次数,再循环中直接使用:
if(A[i] == target)
{
return i;
}
else if(A[i] > target)
{
break;
}
当数组在查找的值大于题目要求的值的时候跳出循环,从数组的最后一个一次赋值向后移动,再将查找的值按照大小排列顺序插入到该数组中。
class Solution {
public:
/*
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: An integer
*/
int searchInsert(vector<int> &A, int target) {
// write your code here
int i, j;
for(i = 0; i < A.size(); i++)
{
if(A[i] == target)
{
return i;
}
else if(A[i] > target)
{
break;
}
}
A.push_back(target);
for(j = A.size(); j >= i; j--)
{
A[j] = A[j - 1];
if(j == i)
{
A[j] = target;
}
}
return i;
}
};
举例测试:
输入存在的数字,便可以显示位置。例如:3,显示1
输入不存在的数字如图所示:输入2,显示插入后的位置为1
2018/1/23
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.
[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)) time
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
[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)) time
在做完6.合并排序数组II之后,系统推荐了一道相似题,就是这道搜索插入位置的题,这道题中也运用到了vector的知识,所以我查了一下基本用法,可以直接使用。例如,我可以运用库中已有函数插入vector<int> A; A.push_back(1);,这样就将整数1插入到了动态数组中。
这道题的挑战在于时间复杂度,因为给定的数组是有序的,所以要在循环中直接判断,这样可以减少循环次数,再循环中直接使用:
if(A[i] == target)
{
return i;
}
else if(A[i] > target)
{
break;
}
当数组在查找的值大于题目要求的值的时候跳出循环,从数组的最后一个一次赋值向后移动,再将查找的值按照大小排列顺序插入到该数组中。
class Solution {
public:
/*
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: An integer
*/
int searchInsert(vector<int> &A, int target) {
// write your code here
int i, j;
for(i = 0; i < A.size(); i++)
{
if(A[i] == target)
{
return i;
}
else if(A[i] > target)
{
break;
}
}
A.push_back(target);
for(j = A.size(); j >= i; j--)
{
A[j] = A[j - 1];
if(j == i)
{
A[j] = target;
}
}
return i;
}
};
举例测试:
输入存在的数字,便可以显示位置。例如:3,显示1
输入不存在的数字如图所示:输入2,显示插入后的位置为1
2018/1/23