第三周 Two Sum

来源:互联网 发布:qq三国70js橙鬼 编辑:程序博客网 时间:2024/06/08 07:39

Two Sum

Leetcode algorithms problem 1:Two Sum

  • 问题描述

    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.

  • 例子

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

  • 思路

    两个循环,第一个循环遍历整个给定数组,第二个循环遍历第一个循环当前下标往后的数,当补码存在即返回结果下标。

代码

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> two(2);        int count = nums.size();        int begin = 0;        int temp;        for(begin; begin < count; begin++) {            two[0] = begin;            temp = target - nums[begin];            for(int i = begin + 1; i < count; i++) {                if(temp == nums[i]) {                    two[1] = i;                    return two;                }            }        }    }};

时间复杂度: O(n^2)
空间复杂度: O(1)


收获&杂谈

继续刷了道简单题找找感觉,这道two sum还是挺简单的,没有复杂度的限制,一开始的思路就可以通过,一些细节一开始没想好导致一开始没通过,debug后成功通过。
查看答案,发现自己的代码少了错误报告语句
throw new IllegalArgumentException(“No two sum solution”);
以及一个解决思路提供了利用map.containsKey这个成员函数来降低时间复杂度,降为了O(n),同时空间复杂度上升为O(n)。

原创粉丝点击