#include <iostream>
#include <vector>
using namespace std;
//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
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int length = nums.size();
for (int i = 0; i < length; i++)
{
if (nums[i] >= target)
{
return i;
}
}
return length;
}
};
//二分搜索法优化我们的时间复杂度
//元素的访问
//
//下标访问: vec[1]; //并不会检查是否越界
//at方法访问: vec.at(1); //以上两者的区别就是at会检查是否越界,是则抛出out of range异常
//访问第一个元素: vec.front();
//访问最后一个元素: vec.back();
//返回一个指针: int* p = vec.data(); //可行的原因在于vector在内存中就是一个连续存储的数组,所以可以返回一个指针指向这个数组。这是是C++11的特性。
class Solution1
{
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
if (nums.back() < target)
{
return nums.size();
}
while(left < right)
{
int mid = left + (right - left)/2; //中间值
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] < target)
{
left = mid + 1;//在mid之后寻找
}
else
{
right = mid;//调整搜索范围
}
}
return right;
}
};
int main()
{
vector<int> nums = { 1, 3, 5, 6 };
int target = 3;
Solution solu;
int ret = solu.searchInsert(nums,target);
Solution1 solu1;
target = 5;
ret = solu1.searchInsert(nums,target);
cout << ret << endl;
system("pause");
return 0;
}
自己训练代码:
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
//二分搜索法
int searchInsert(vector<int>& nums, int target) {
int beg = 0, end = nums.size() - 1;
if (nums.back() < target)
{
return nums.size();
}
while (beg < end)
{
int mid = beg + (end - beg) / 2; //中间值
if (nums[mid] > target) //在前半部分
{
end = mid;//调整搜索范围
}
else if (nums[mid] < target)//在后半部分
{
beg = mid + 1;//在mid之后寻找
}
else//刚好相等时候
{
return mid;
}
}
return end;
}
};
int main()
{
vector<int> nums = { 1, 3, 5, 6 };
int target = 4;
Solution solu;
int ret = solu.searchInsert(nums,target);
cout << ret << endl;
system("pause");
return 0;
}
补充知识点:
介绍
- vector是表示可变大小数组的序列容器。
- 就像数组一样,vector也采用的连续存储空间来存储元素。也就是意味着可以采用下标对vector的元素进行访问,和数组一样高效。但是又不像数组,它的大小是可以动态改变的,而且它的大小会被容器自动处理。
- 本质讲,vector使用动态分配数组来存储它的元素。当新元素插入时候,这个数组需要被重新分配大小为了增加存储空间。其做法是,分配一个新的数组,然后将全部元素移到这个数组。就时间而言,这是一个相对代价高的任务,因为每当一个新的元素加入到容器的时候,vector并不会每次都重新分配大小。
- vector分配空间策略:vector会分配一些额外的空间以适应可能的增长,因为存储空间比实际需要的存储空间更大。不同的库采用不同的策略权衡空间的使用和重新分配。但是无论如何,重新分配都应该是对数增长的间隔大小,以至于在末尾插入一个元素的时候是在常数时间的复杂度完成的。
- 因此,vector占用了更多的存储空间,为了获得管理存储空间的能力,并且以一种有效的方式动态增长。
- 与其它动态序列容器相比(deques, lists and forward_lists), vector在访问元素的时候更加高效,在末尾添加和删除元素相对高效。对于其它不在末尾的删除和插入操作,效率更低。比起lists和forward_lists统一的迭代器和引用更好。
用法
1. 头文件
2. vector声明及初始化
vector<int> vec;
vector<int> vec(5);
vector<int> vec(10, 1);
vector<int> vec(tmp);
vector<int> tmp(vec.begin(), vec.begin() + 3);
int arr[5] = {1, 2, 3, 4, 5};
vector<int> vec(arr, arr + 5);
vector<int> vec(&arr[1], &arr[4]);
3. vector基本操作
(1). 容量
- 向量大小: vec.size();
- 向量最大容量: vec.max_size();
- 更改向量大小: vec.resize();
- 向量真实大小: vec.capacity();
- 向量判空: vec.empty();
- 减少向量大小到满足元素所占存储空间的大小: vec.shrink_to_fit(); //shrink_to_fit
(2). 修改
- 多个元素赋值: vec.assign(); //类似于初始化时用数组进行赋值
- 末尾添加元素: vec.push_back();
- 末尾删除元素: vec.pop_back();
- 任意位置插入元素: vec.insert();
- 任意位置删除元素: vec.erase();
- 交换两个向量的元素: vec.swap();
- 清空向量元素: vec.clear();
(3)迭代器
- 开始指针:vec.begin();
- 末尾指针:vec.end(); //指向最后一个元素的下一个位置
- 指向常量的开始指针: vec.cbegin(); //意思就是不能通过这个指针来修改所指的内容,但还是可以通过其他方式修改的,而且指针也是可以移动的。
- 指向常量的末尾指针: vec.cend();
(4)元素的访问
- 下标访问: vec[1]; //并不会检查是否越界
- at方法访问: vec.at(1); //以上两者的区别就是at会检查是否越界,是则抛出out of range异常
- 访问第一个元素: vec.front();
- 访问最后一个元素: vec.back();
- 返回一个指针: int* p = vec.data(); //可行的原因在于vector在内存中就是一个连续存储的数组,所以可以返回一个指针指向这个数组。这是是C++11的特性。
(4)算法
vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
cout << *it << endl;
for (size_t i = 0; i < vec.size(); i++) {
cout << vec.at(i) << endl;
}
#include <algorithm>
reverse(vec.begin(), vec.end());
sort(vec.begin(), vec.end()); //采用的是从小到大的排序
//如果想从大到小排序,可以采用上面反转函数,也可以采用下面方法:
bool Comp(const int& a, const int& b) {
return a > b;
}
sort(vec.begin(), vec.end(), Comp);
二分查找又称折半查找,对排好序的数组,每次取这个数和数组中间的数进行比较,复杂度是O(logn)如:设数组为a[n],查找的数x,
如果x==a[n/2],则返回n/2;
如果x < a[n/2],则在a[0]到a[n/2-1]中进行查找;
如果x > a[n/2],则在a[n/2+1]到a[n-1]中进行查找;
优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。
条件:查找的数组必须要为有序数组。
1、二分查找可以解决的问题:二分查找可以解决预排序数组的查找问题。只要数组中包含T(即要查找的值),那么通过不断的缩小包含T的范围,最终就可以找到它。一开始,范围覆盖整个数组,将数组的中间项与T进行比较,可以排除一般的元素,范围缩小一半。就这样反复比较反复缩小范围,最终就会在数组中找到T,或者确定原以为T所在的范围实际为空。对于包含N个元素的表,整个查找过程大约要经过Log(2)N次比较。
注意:二分查找是针对有序的数组而言的。
#include<iostream>
using namespace std;
//从效率上看,使用移位指令有更高的效率,因为移位指令占2个机器周期,而乘除法指令占4个机器周期。
//从硬件上看,移位对硬件更容易实现,所以会用移位,移一位就乘2, 这种乘法当然考虑移位了
//int binary_search(int arr[], int n, int key)
//{
// int left = 0; //数组的首位置,即arr[0]处
// int right = n - 1;//数组的最后一个位置,即arr[n-1],数组大小为n
//
// //循环条件一定要注意
// while (left <= right)
// {
// int mid = left + ((right - left) >> 1);//此处的mid的计算一定要放在while循环内部,否则mid无法正确更新;并且此处用移位代替除以2可以提高效率,而且可以防止溢出。
// if (arr[mid] > key)//数组中间的位置得数大于要查找的数,那么我们就在中间数的左区间找
// {
// right = mid - 1;
// }
// else if (arr[mid] < key)//数组中间的位置得数小于要查找的数,那么我们就在中间数的右区间找
// {
// left = mid + 1;
// }
// else
// {
// return mid;//中间数刚好是要查找的数字。
// }
// }
//
// //执行流如果走到此处说明没有找到要查找的数字。
// return -1;
//}
/*
归的二分查找
arrat:数组 , low:上界; high:下界; target:查找的数据; 返回target所在数组的下标
推荐使用非递归的方式,因为递归每次调用递归时有用堆栈保存函数数据和结果。能用循环的尽量不用递归。
*/
int binarySearch(int array[], int low, int high, int target) {
int middle = (low + high) / 2;
if (low > high) {
return -1;
}
if (target == array[middle]) {
return middle;
}else if (target < array[middle]) {
return binarySearch(array, low, middle - 1, target);
}else if(target > array[middle]) {
return binarySearch(array, middle + 1, high, target);
}
return -1;
}
//测试用例如下所示:
void main()
{
int arr[5] = { 1, 3, 5, 9, 10 };
int ret1 = 0, ret2 = 0, ret3 = 0;
ret1 = binarySearch(arr,0,4,9);
cout << ret1 << endl;
ret2 = binarySearch(arr,0,4,5);
cout << ret2 << endl;
ret3 = binarySearch(arr,0,4,2);
cout << ret3 << endl;
system("pause");
}
3、二分查找代码需要注意的地方:
right=n-1-------->while(left <= right)-------->right=mid-1;
right=n-------->while(left < right)-------->right=mid;
此外:大部分人喜欢在最开始就判断arr[mid]与key相等,但是这样是不明智的,因为相等情况在大多状况下都是少数,写在开始的话,每次循环都需要判断一次相等,浪费时间,效率太低。
复习:
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int binary_search(vector<int>& nums, int target)
{
int left = 0; //数组的首位置,即arr[0]处
int right = nums.size() - 1;//数组的最后一个位置,即arr[n-1],数组大小为n
while (left <= right)
{
int mid = left + ((right - left) >> 1);//此处的mid的计算一定要放在while循环内部,否则mid无法正确更新;并且此处用移位代替除以2可以提高效率,而且可以防止溢出。
if (nums[mid] > target)//要找的元素在前半部分
{
right = mid - 1;//如果是,忽略掉后半部分,在mid前寻找
}
else if (nums[mid] < target)//要找的元素在后半部分
{
left = mid + 1;//如果是,请忽略掉前半部分,在mid后寻找
}
else//中间数刚好是要查找的数字
{
return mid;
}
}
//执行流如果走到此处说明没有找到要查找的数字。
return -1;
}
};
//测试用例如下所示:
void main()
{
vector<int> arr = { 1, 3, 5, 9, 10 };
int ret1 = 0, ret2 = 0, ret3 = 0;
Solution solu;
ret1 = solu.binary_search(arr,9);
cout << ret1 << endl;
ret2 = solu.binary_search(arr,5);
cout << ret2 << endl;
ret3 = solu.binary_search(arr,2);
cout << ret3 << endl;
system("pause");
}