刷LeetCode的第一题,TwoSum,基本算是水过。

题目:https://leetcode.com/problems/two-sum/

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

分析:给出一个数组,和一个目标值target,请在数组中找出两个元素值的和等于该目标值的,并返回其数组索引(从1开始的索引)。题意相当简单。作为刷LC的第一道题,没有多想,这种与数组的某个特征值相关的问题,先排个序总是没错的。可以先从小到大sort一下,然后给扔两个指针到数组头尾,开始寻找满足要求的值。直接上代码。

 typedef struct Node
{
int id,val;
}node;
bool cmp(const Node& n1,const Node& n2)
{
return n1.val < n2.val;
//定义的比较函数,按照节点值(也就是输入数组值)从小到大排列
}
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
Node nodes[len];
for(int i = ; i<len ; i++ )
{
nodes[i].id = i+;//不是从0开始,而是从1开始的索引。
nodes[i].val = nums[i];
}
sort(nodes,nodes+len,cmp);
int ptr1 = ,ptr2 = len-;//设置头尾指针
std::vector<int> ans;
while(ptr1<ptr2)
{
if(nodes[ptr1].val+nodes[ptr2].val == target)
{
if(nodes[ptr1].id>nodes[ptr2].id)
swap(nodes[ptr1].id,nodes[ptr2].id);
ans.push_back(nodes[ptr1].id);
ans.push_back(nodes[ptr2].id);//将答案放进ans
return ans;
}
else if(nodes[ptr1].val+nodes[ptr2].val < target)
ptr1++;//向后移动头指针
else
ptr2--;//向前移动尾指针
}
}
};

runtime还可以,比98%的CPP提交代码要快。

这个

Your runtime beats 98.59% of cpp submissions.

[LeetCode] Two Sum水过的更多相关文章

  1. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  2. LeetCode:柠檬水找零【860】

    LeetCode:柠檬水找零[860] 题目描述 在柠檬水摊上,每一杯柠檬水的售价为 5 美元. 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯. 每位顾客只买一杯柠檬水,然后向 ...

  3. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  4. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  5. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  6. [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  7. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  8. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  9. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

随机推荐

  1. Webstorm10.0.4注册码

    分享几个Webstorm10的注册码: (1) user name :EMBRACE ===== LICENSE BEGIN =====17739-1204201000002KkN!4z2O8JEyj ...

  2. 在TNSNAMES.ORA文件中配置本机装的oracle

    首先,感谢这两位网友:http://zhidao.baidu.com/link?url=eGYeoEa-EhQdVitSGqjE36uNfVmEsryXH1WUjPue6YvArDSx-Y1N9_rd ...

  3. uva 11151

    求最长回文串  就是将字符串翻转后求最长公子列..... #include <cstdio> #include <cstdlib> #include <algorithm ...

  4. C/C++语言参数传递----函数/方法 参数的指针引用传递

    int m_value = 1; void func(int *p) { p = &m_value; } int main(int argc, char *argv[]) { int n = ...

  5. module_init宏解析 linux驱动的入口函数module_init的加载和释放

    linux驱动的入口函数module_init的加载和释放 http://blog.csdn.net/zhandoushi1982/article/details/4927579 void free_ ...

  6. Spring RestTemplate介绍

    http://www.cnblogs.com/rollenholt/p/3894117.html RestTemplate 这篇文章打算介绍一下Spring的RestTemplate.我这边以前设计到 ...

  7. fork、vfork、clone区别

    在Linux中主要提供了fork.vfork.clone三个进程创建方法. 问题 在linux源码中这三个调用的执行过程是执行fork(),vfork(),clone()时,通过一个系统调用表映射到s ...

  8. 隐马尔科夫模型 介绍 HMM python代码

    #HMM Forward algorithm #input Matrix A,B vector pi import numpy as np A=np.array([[0.5,0.2,0.3],[0.3 ...

  9. python学习笔记二--列表的使用

    一.基本列表操作 1. 合并‘+’:左右两边必须均为列表 可以用str(),%,list()做类型的转换后再做合并 2. 重复‘*’: 3. 迭代和解析: x作为for循环里步进变量,由于列表是序列, ...

  10. PHP+Mysql无限分类的方法汇总

    无限分类是个老话题了,来看看PHP结合Mysql如何实现.第一种方法这种方法是很常见.很传统的一种,先看表结构表:categoryid int 主键,自增name varchar 分类名称pid in ...