第三周 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)。
阅读全文
0 0
- 第三周 Two Sum
- 第十周:1. Two Sum
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- LeetCode-66-Plus One 水题
- 机器人项目部分数据本地化——工厂模式+策略模式实现
- 欢迎使用CSDN-markdown编辑器
- 布隆过滤器
- Qt 程序编译时提示:The CDB process terminated
- 第三周 Two Sum
- smoj2020(平衡树优化dp)
- 机器学习中的标准化/归一化
- APUE 第6-9章
- cygwin安装
- 兄弟连LinuxStudyNote(3)-给Linux初学者的建议-服务器管理和运维建议(二)linux各目录的作用
- 如何选择 compileSdkVersion, minSdkVersion 和 targetSdkVersion
- Java学习笔记(一)Java运行机制及JVM相关
- 编程题目录(待整理)