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. 重新复习~ 为了重新找工作 - > XMLHttpRequest2.0 Jsonp nodeType 节点 webpack基本搭建 闭包的一句话总结

    XMLHttpRequest2.0 1.可以设置超时 (xhr.timeout = 1000; ontimeout()函数) 2.支持FormData对象管理表单数据(new FormData 方法: ...

  2. StringBuffer&StringBuilder

    对字符串修改时,用到StringBuffer&StringBuilder,能够多次修改对象并且不产生新的未使用对象 StringBuilder线程不安全(不能同步访问),速度有优势,多数情况下 ...

  3. java的重写

    重写是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变.即外壳不变,核心重写! 重写的好处在于子类可以根据需要,定义特定于自己的行为. 也就是说子类能够根据需要实现父类的方法 ...

  4. maven管理jar,pom.xml导入spring依赖

    <properties> <junit.version>4.12</junit.version> <spring.version>4.3.9.RELEA ...

  5. python初学代码留个纪念

    最简单的代码  if   else if  else 1.python中else if   用  elif表示 2.注释: 单行注释:##### 多行注释:''' ------''',"&q ...

  6. Shell 字符串处理

    字符串处理方式 计算字符串长度 获取子串在字符串中的索引位置 计算子串长度 抽取(截取)字串 1.计算字符串长度,有两种方式 $ ${#string} $ expr length "$str ...

  7. js设置按钮的灰色不可点击

    document.getElementById("btnSave").setAttribute("disabled", true);//设置不可点击 docum ...

  8. Android日常问题整理

    1.系统语言切换后Activity布局刷新问题 4.2增加了一个layoutDirection属性,当改变语言设置后,该属性也会成newConfig中的一个mask位.所以ActivityManage ...

  9. springboot +mybatis 搭建完整项目

    springboot + mybatis搭建完整项目 1.springboot整合mybatis注解版 转:https://blog.csdn.net/u013187139/article/detai ...

  10. python基础—购物车小程序练习

    要求:顾客可以根据商品编号购买工资允许内的商品,购买完成后,打印购买列表. def main(): salary = input("what is your salary ?") ...