1-Two Sum @LeetCode
1-Two Sum
题目
思路
题目中得到的信息有:
- 都是整数,并且可正可负,也可一个值包含多个;
- 只有一个正确的结果。
方法一:
最直接的思路就是两重循环遍历,时间复杂度是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的更多相关文章
- Path Sum [LeetCode]
Problem Description: http://oj.leetcode.com/problems/path-sum/ Pretty easy. /** * Definition for bin ...
- 39. Combination Sum - LeetCode
Question 39. Combination Sum Solution 分析:以candidates = [2,3,5], target=8来分析这个问题的实现,反向思考,用target 8减2, ...
- 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 ...
- 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. ...
- Combination Sum [LeetCode]
Problem Description: http://oj.leetcode.com/problems/combination-sum/ Basic idea: It seems complicat ...
- two Sum ---- LeetCode 001
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- Minimum Size Subarray Sum -- leetcode
题目描写叙述: Given an array of n positive integers and a positive integer s, find the minimal length of a ...
- Minimum Size Subarray Sum —— LeetCode
Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...
- 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 ...
- 【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 ...
随机推荐
- 关于angular实现表单的一些问题
如何用angular实现表单的一些问题?核心步骤大概如下: 创建模型类 创建控制此表单的组件. 创建具有初始表单布局的模板. 使用ngModel双向数据绑定语法把数据属性绑定到每个表单输入控件. 往每 ...
- Main Steps to Setup an ODI data sync
0. Get ODI installed 1. Topo physical Architecture/new physical schema 2. New Logical schema 3. New ...
- vue实现pc端上拉加载功能,不兼容移动端
所用插件:Mock.js 这个只用到它简单的功能,拦截ajax请求. vue和axios,vue基础知识请看文档. axios类似于jquery的ajax方法. 以下是是该功能所有代码,其中mock的 ...
- 为什么毕业一年了工资还是只有7K
“天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能.”. 从实习的时候开始说起吧,实习的时候是在上海的一家做winform的公司,这家公司总是会 ...
- 使用restTemplate来访问https
1.maven: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId& ...
- 结对编程总结(胡超慧&&王宇)
在分析完需求的几秒中内,我和搭档就蒙了,因为之前并没有做过UI,因此这次的项目对于我们来说无疑是一个陌生的挑战. 为了最大程度实现曾经代码的复用,我们最开始考虑使用可以支持C++的QT来进行相关的设计 ...
- linux 常见技巧
1.# :表示权限用户(如:root) $:表示普通用户 开机提示:login:输入用户名 password:输入口令 用户是系统注册用户成功登陆后, 可以进入相应的用户环境. 退出当前shell,输 ...
- 使用Selenium进行浏览器自动化操作记录
一位经验丰富的同事交给了我一个任务:将20个IP地址添加到公司系统对应的目录下. 这个任务之前做过,并且数量是远不止20个,当时就学习Selenium并且使用Python3.6写了一个脚本用来自动化地 ...
- 关于TCP和MQTT之间的转换(转载)
现在物联网流行的就是MQTT 其实MQTT就是在TCP的基础上建立了一套协议 可以看这个,本来我自己想用Wireshark监听一下,不过百度一搜索一大把,我就不测试了 https://blog.csd ...
- 纯粹的python绑定
目前很多学习资料这样解释赋值与绑定,当是一个简单变量时,是赋值,当是复合变量时,是绑定. 注:赋值是重新复制变量到新变量中,赋值前后两个变量之间无联系.例C语言中: int a=6: int b: b ...