2019-07-25 [日三省吾身] LeetCode1 Two

2019-07-25  本文已影响0人  荻庐夜雪

写在前面:

作为一个编程小白打算通过LeetCode刷题自学C++,特此不定期记录整理解题思路。


题目一:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:
给定 nums =\left[2, 7, 11, 15\right], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum


第一次尝试:

思路:刚开始想法很简单,按顺序选定其中一个数,然后从后一个数开始按顺序遍历查找和为目标值的数。这个思路虽然避免了重复利用数组中同样的元素这一条件,即[2,3,5], 6输出为[2,2]的情况。但是对于特殊情况下输出可能会有多组答案,即[2,7,11,16],18 输出为[0,3,1,2]的情况。
后续还需要再做改进。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        //Retrieve an array
        for (int i = 0; i < nums.size();i++) {
            temp1 = nums[i];
            temp2 = target - temp1;
            for (int j = i + 1; j < nums.size(); j++) {
                if (nums[j] == temp2) {
                    number_index.push_back(i);
                    number_index.push_back(j);
                }
            }
        }
        return number_index;
    }

public:
    vector<int> number_index;
    int temp1;
    int temp2;
};

执行用时:404 ms;内存消耗 9.3MB


题目二:

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。函数应该返回这两个下标值 index1 和 index2,其中 index1$必须小于index2。

说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

示例:
给定 nums =\left[2, 7, 11, 15\right], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted


待续。

上一篇 下一篇

猜你喜欢

热点阅读