总结今天所用到的vector的知识
insert
[ ]
iterator insert (iterator position, const value_type& val);
在position位置插入val,返回迭代器;- [ ]
void insert (iterator position, size_type n, const value_type& val);
在position位置插入n个val,没有返回值; - [ ]
void insert (iterator position, InputIterator first, InputIterator last);
在position位置插入从fisrt迭代器开始到last迭代器位置的元素,包括fisrt,不包括last。
erase
- [ ]
iterator erase (iterator position);
删除position位置的元素,随机返回迭代器,小心野指针; - [ ]
iterator erase (iterator first, iterator last);
删除从first到last位置的元素,包括first,不包括last。 push_back
push最后一个元素pop_back
pop最后一个元素remove
- Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:You must do this in-place without making a copy of the array.
Minimize the total number of operations.
void Solution283::moveZeroes(vector<int>& nums)
{
vector<int>::iterator pre = nums.begin();
vector<int>::iterator i;
int k = 0;
while (pre < nums.end())
{
if (*pre == 0)
{
++k;
i = pre;
nums.erase(i);
}
else
pre++;
}
nums.insert(nums.end(), k, 0);
}
收获:
1. while循环每次判断的时候,应该判断nums.end()
因为如果提前赋值it=nums.end()-1
,每次删除数组中元素,会导致it迭代器越界
2. 在循环中执行nums.erase(it)
时,执行完毕会随机返回迭代器,如果提前赋值会使迭代器称为野指针,便不能执行++
操作
3. insert
在末尾插入位置为nums.end()
- Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
扫描二维码关注公众号,回复: 2423511 查看本文章Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
void Solution189::rotate(vector<int>& nums, int k)
{
if (nums.size() < k) k = k % nums.size();
nums.insert(nums.begin(), nums.end() - k, nums.end());
nums.erase(nums.end() - k, nums.end());
}
收获:
1. 这里学习了别人的代码,在数组长度小于k的时候重新对k取余赋值,实际上前面的数组长度的整数倍的转换都是多余的
2. 这时候就可以利用insert
方法,先插入,再统一删除
- Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
vector<int>::iterator p = numbers.begin();
vector<int>::iterator q = numbers.end();
--q;
vector<int> index;
while (p < q)
{
if ((*p + *q) < target)
{
++p;
}
else if ((*p + *q) > target)
{
--q;
}
else
{
index.push_back(p - numbers.begin() + 1);
index.push_back(q - numbers.begin() + 1);
break;
}
}
return index;
收获:
1. 算法思想:两个指针指向前后,分别判断和target的大小,如果大后面指针前移,如果小前面指针后移