c++ tle leetcode 反转 pac ber cap 清空
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
- Given nums = [2, 7, 11, 15],
- target = 9,
- Because nums[0] + nums[1] = 2 + 7 = 9,
- return [0, 1].
- C++:
- class Solution {
- public: vector < int > twoSum(vector < int > &nums, int target) {
- vector < int > ans;
- for (int i = 0; i < nums.size() - 1; i++) {
- for (int j = i + 1; j < nums.size(); j++) {
- if (nums[i] + nums[j] == target) {
- ans.push_back(i);
- ans.push_back(j);
- break;
- }
- }
- }
- return ans;
- }
- };
Java:
- public class Solution {
- public int[] twoSum(int[] nums, int target) {
- int[] a = new int[2];
- for (int i = 0; i) {
- for (int j = i + 1; j <= nums.length - 1; j++) {
- if (nums[i] + nums[j] == target) {
- a[0] = i;
- a[1] = j;
- break;
- }
- }
- }
- return a;
- }
- }
附加一下 c++ vector 的简单用法:
1.push_back 在数组的最后添加一个数据
2.pop_back 去掉数组的最后一个数据
3.at 得到编号位置的数据
4.begin 得到数组头的指针
5.end 得到数组的最后一个单元 + 1 的指针
6.front 得到数组头的引用
7.back 得到数组的最后一个单元的引用
8.max_size 得到 vector 最大可以是多大
9.capacity 当前 vector 分配的大小
10.size 当前使用数据的大小
11.resize 改变当前使用数据的大小,如果它比当前使用的大,者填充默认值
12.reserve 改变当前 vecotr 所分配空间的大小
13.erase 删除指针指向的数据项
14.clear 清空当前的 vector
15.rbegin 将 vector 反转后的开始指针返回 (其实就是原来的 end-1)
16.rend 将 vector 反转构的结束指针返回 (其实就是原来的 begin-1)
17.empty 判断 vector 是否为空
18.swap 与另一个 vector 交换数据
Leetcode Array 1 twoSum
来源: http://www.bubuko.com/infodetail-2224731.html