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].
大致的意思是:
给定一个数组(vector),在传入一个target,找出其中两个数字加和为target的数字的下标,并返还回来。
解析:
这个题是Easy范围的,因为输入的数字都是无序的,所以使用暴力法就可以了,两个for循环遍历搞定。
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> vec;
int n = nums.size();
for(int i=0;i<n-1;i++)
for (int j = i + 1; j <= n - 1; j++)
{
if (nums[i] + nums[j] == target)
{
vec.push_back(i);
vec.push_back(j);
return vec;
}
}
return vec;
}
};
int main()
{
//2 7 11 15
vector<int> nums,out;
nums.push_back(3);
nums.push_back(2);
nums.push_back(4);
// nums.push_back(15);
int target = 6;
Solution so;
out=so.twoSum(nums, target);
cout << out[0] << ' ' << out[1] << endl;
system("pause");
return 0;
}
拓展一下,如果现在给的是有序的递增数组,该怎么操作呢?
一个指针在前边一个指针在后边,开始叠加,如果两个数字的和大于target,后边的指针向前走,如果两个数字的和小于target,前边的指针向后移动一位。时间复杂度是O(n)。
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int p2 = nums.size()-1;
int p1 = 0;
vector<int> vec;
while (p1 != p2)
{
if (nums[p1] + nums[p2] == target)
{
vec.push_back(p1);
vec.push_back(p2);
return vec;
}
else if (nums[p1] + nums[p2] > target)
{
p2--;
}
else {
p1++;
}
}
return vec;
}
};
int main()
{
//2 7 11 15
vector<int> nums,out;
nums.push_back(2);
nums.push_back(3);
nums.push_back(11);
nums.push_back(15);
int target = 9;
Solution so;
out=so.twoSum(nums, target);
cout << out[0] << ' ' << out[1] << endl;
system("pause");
return 0;
}
===================================================
public boolean[] isSecure(int[][] incompatibility, List<Integer>[] containers){
boolean[] returnNum = new boolean[containers.length];
for(int i=0;i<containers.length;i++){
returnNum[i] = true;
}
int numIncompatibility = incompatibility.length;
Map<Integer,List<Integer>> unComfortableMap = new HashMap<>();
for(int i=0;i<numIncompatibility;i++){
List<Integer> newList = unComfortableMap.get(incompatibility[i][0]);
newList.add(incompatibility[i][1]);
unComfortableMap.put(incompatibility[i][0],newList);
}
for(int i=0;i<containers.length;i++){
List<Integer> listTemp = containers[i];
for(Integer temp :listTemp){
if(unComfortableMap.keySet().contains(temp)){
for(Integer getNum: unComfortableMap.get(temp) ){
if(listTemp.contains(getNum)){
returnNum[i] = false;
break;
}
}
}
}
}
return returnNum;
}