为了明年的春招,小增也打算用LeetCode刷刷题。刚刚接触这款在线平台,对其不甚熟悉,具体的使用介绍请参照博客:https://blog.csdn.net/seabiscuityj/article/details/80730733
言归正传,今天做的题比较简单,具体题目如下:
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]
解答注意事项:
1.假如输入是[2, 7, 11, 15], 目标是9,直接两层for循环会先得到下标0,1,后得到下标1,0,并且最终的输出是后面一次覆盖掉前一次的结果,致使所得结果与期望结果不符。
2.假如输入是[3,2,4], 目标是6,当避免了第一个问题后再直接两层for循环会得到下标0,0,这个bug就是第一个元素3被加了2遍,致使所得结果与期望结果不符。
小增C++答案(Accepted):
方法一(暴力法):
class Solution {
public:
vector twoSum(vector& nums, int target) {
int arr[] = {0,0};
vector SiteElements(arr, arr + sizeof(arr)/sizeof(int));
int k=0;
for( int i = 0; i
方法二(先用under_map型变量记录原始数组的位置,然后再用排序算法对原始数组进行排序,最后用二分搜索法求得最终结果):
#include
#include
#include
#include
using namespace std;
class Solution {
public:
vector insertSort(vector &nums) {
for (int i = 1; i < nums.size(); i++)
for (int j = i; j >= 0; j--)
if (nums[j] < nums[j - 1])
swap(nums[j], nums[j - 1]);
else
break;
return nums;
}
vector twoSum(vector &numbers, int target, unordered_maprecordcount, unordered_maprecordsite) {
vector nums = {0, 0};//因为返回值要求是向量,所以必须得创建一个向量去装索引
for (int i = 0; i < numbers.size(); i++) {
int l = 0, r = numbers.size() - 1; //二分搜索算法开始
while (l <= r) { //二分搜索算法这里一般是while
int mid = l + (r - l) / 2; //避免了使用加法,因为加法容易产生溢出
if (target - numbers[i] == numbers[mid] && mid != i) // 加上mid != i这个条件是为了避免同一个数被加两次,致使返回的索引一样。
{
nums[0] = recordsite[target - numbers[i]];
nums[1] = recordsite[numbers[i]];
return nums;
}
if (target - numbers[i] < numbers[mid])//更新边界
r = mid - 1;
else
l = mid + 1;
}
}
return nums;
}
};
int main(){
vector nums = {3,2,1,4,5,6};
vector result = {0,0};
unordered_map recordcount;
unordered_map recordsite;
for (int i = 0; i < nums.size(); i++) {
recordcount[nums[i]]++;
recordsite[nums[i]] = i;
}
nums = Solution().insertSort(nums);
result = Solution().twoSum(nums, 3, recordcount, recordsite);
for (int i=0; i
日积月累,与君共进,增增小结,未完待续。