1-Two Sum

题目

思路

题目中得到的信息有:

  1. 都是整数,并且可正可负,也可一个值包含多个;
  2. 只有一个正确的结果。

方法一:

最直接的思路就是两重循环遍历,时间复杂度是O(n^2),这样肯定不行。

方法二:

由于是乱序的,1)可以先排序,2)然后再遍历一遍就可以找到结果。排序的话不能再原来的基础上进行,这样就破坏了下标顺序,因此需要申请额外的空间,用于保存他们的索引,然后再该空间上进行排序。时间复杂度是[排序O(logn) + 查找O(n)],空间复杂度是O(n)。

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numSize, int target) {
int *tmp = (int *)malloc(sizeof(int) * numSize);//申请额外空间
for (int i = 0; i < numSize; i++)
tmp[i] = i; //初始化 for (int i = 1; i < numSize; i++) { //采用的是插入排序
int value = tmp[i];
int j;
for ( j = i - 1; j >= 0; j--) {
if (nums[value] < nums[tmp[j]]) {
tmp[j+1] = tmp[j];
} else {
break;
}
}
tmp[j+1] = value;
} int i = 0, j = numSize - 1;
while (i < j) { //遍历寻找结果
int ret = nums[tmp[i]] + nums[tmp[j]] - target;
if (ret == 0)
break;
if (ret > 0) j--;
else
i++;
}
int *ret = NULL;
if (i < j) {
ret = (int *)malloc(2*sizeof(int));
if (tmp[i] < tmp[j]) {
ret[0] = tmp[i] + 1;
ret[1] = tmp[j] + 1;
} else {
ret[1] = tmp[i] + 1;
ret[0] = tmp[j] + 1;
}
}
free(tmp);
return ret;
}

结果

方法三:

方法二是通过两个值找target,可以换个思路通过一个值和target找另一个值。这种思路需要额外的数据结构,该数据结构必须要满足1)值和下标都能保存;2)可以快速查找出是否包含指定值。hashmap满足该条件。以值作为key,下标作为value。由于hashmap不能有重复key,题目有是允许一个值包含多个,这样可以吗?

两种情况:1)所求的结果值都是一样的,这样的话一个在hashmap中,另一个还没有插入进去,就找到正确的结果了;2)不相等,并且一个值为多个相同值中的一个,这样会将多个相同值插入到hashmap中,但题目中说正确结果只有一个,因此这种情况不会出现,所以hashmap完全满足该题目。

c版本

//采用数组方式存储,冲突的解决是最简单的,线性增加
typedef struct node {
int index; //下标
int value; //值
}node; //从hash中取特定值,若没有返回-1
int hash_get(node *hash, int numSize, int value) {
int i = (unsigned int)value % numSize;
while (hash[i].index != -1) {
if (hash[i].value == value)
break;
i = (i + 1) % numSize;
}
return hash[i].index;
} //将值和下标放入到hash中
void hash_put(node *hash, int numSize, int value, int index)
{
int i = (unsigned int)value % numSize;
while (hash[i].index != -1) {
i = (i + 1) % numSize;
}
hash[i].index = index;
hash[i].value = value;
} int* twoSum(int* nums, int numSize, int target) {
node *hash = (node *)malloc(numSize * sizeof(node));
for (int i = 0; i < numSize; i++)
hash[i].index = -1;
int index;
int *ret = NULL;
for (int i = 0; i < numSize; i++) {
index = hash_get(hash, numSize, target - nums[i]);
if (index == -1)
hash_put(hash, numSize, nums[i], i);
else {
ret = (int *)malloc(2*sizeof(int));
ret[0] = index + 1;
ret[1] = i + 1;
break;
}
}
free(hash);
return ret; }

结果

java版本


public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) { //一遍遍历
Integer value = map.get(target - nums[i]); //在hashmap中取值
if (value == null) //若没有,则插入
map.put(nums[i], i);
else { //有,则说明已经找到
int[] ret = new int[2];
ret[0] = value + 1;
ret[1] = i + 1;
return ret;
}
}
return null;
}

结果

1-Two Sum @LeetCode的更多相关文章

  1. Path Sum [LeetCode]

    Problem Description: http://oj.leetcode.com/problems/path-sum/ Pretty easy. /** * Definition for bin ...

  2. 39. Combination Sum - LeetCode

    Question 39. Combination Sum Solution 分析:以candidates = [2,3,5], target=8来分析这个问题的实现,反向思考,用target 8减2, ...

  3. Minimum Path Sum [LeetCode]

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...

  4. Nested List Weight Sum -- LeetCode 339

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  5. Combination Sum [LeetCode]

    Problem Description: http://oj.leetcode.com/problems/combination-sum/ Basic idea: It seems complicat ...

  6. two Sum ---- LeetCode 001

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  7. Minimum Size Subarray Sum -- leetcode

    题目描写叙述: Given an array of n positive integers and a positive integer s, find the minimal length of a ...

  8. Minimum Size Subarray Sum —— LeetCode

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  9. Minimum Path Sum——LeetCode

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...

  10. 【LeetCode】Path Sum ---------LeetCode java 小结

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

随机推荐

  1. GC 是什么? 为什么要有GC?

    C/C++中由程序员进行对象的回收像学校食堂中由学生收盘子,.Net 中由GC 进行垃圾回收像餐馆中店员 去回收. GC 是垃圾收集器(Garbage Collection).程序员不用担心内存管理, ...

  2. python的迭代器

    迭代器 我们已经知道,可以直接作用于for循环的数据类型有以下几种: 一类是集合数据类型,如list.tuple.dict.set.str等: 一类是generator,包括生成器和带yield的ge ...

  3. 存储过程 传 datatable

    首先  定义 datatable 然后把要传的数据放到table里面 调用 存储过程   传递参数

  4. 【转】IE沙箱拖拽安全策略解析

    https://xlab.tencent.com/cn/2015/12/17/ie-sandbox-drop-security-policy/ IE沙箱逃逸是IE浏览器安全研究的一个重要课题,其中有一 ...

  5. 使用VBA轻松实现汉字与拼音的转换

    Function pinyin(p As String) As String i = Asc(p) Select Case i Case -20319 To -20318: pinyin = &quo ...

  6. MVC部署阿里云躺过的坑

    1.端口问题 服务器上的80端口默认是打开的.但要能用必须在阿里云的安全组添加对应的配置. 2.安装IIS 在Windows Service 2012 安装IIS,安装时勾一个总复选框,但有些该分支下 ...

  7. Linux命名空间

    Linux Namespaces机制提供一种资源隔离方案.PID,IPC,Network等系统资源不再是全局性的,而是属于特定的Namespace.每个Namespace里面的资源对其他Namespa ...

  8. java 中根据类的属性排序

    package edu.del; import java.util.ArrayList; import java.util.Collections; import java.util.List; im ...

  9. 2018-计算机系机试(第二批)-B-二进制输出

    B. 二进制输出 单点时限: 1.0 sec 内存限制: 256 MB 输入一个十进制表示的非负整数,输出其 8 位二进制表示. 例如:输入 10 ,输出 00001010. 输入格式 一行一个非负整 ...

  10. 使用VMware Workstation 14 Player或者Oracle VM VirtualBox安装Fedora-Workstation-netinst-x86_64-27-1.6操作系统的相关记录

    无论是在使用哪个(VMware或者Oracle VM)都遇到了一个问题:即使在安装完Fedoras操作系统之后,进行Reboot还是会进入之前一摸一样的安装界面,相当于再次安装.然而最最有效的解决办法 ...