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 ...
随机推荐
- 使用eclipse整合ssh项目的例子--lljf(1)
最近向自己单独做一个基于ssh的项目,来预习和巩固自己的Java基础.找了一个实际生活中的定做衣服的例子来做一做,放到博客上给大家一起分享学习,后边会持续更新项目编写时候遇到的困难和使用的技术等. 1 ...
- sql在所有存储过程中查询包含某字符串的执行语句
直接在查询分析器中执行以下代码就行: 方法一) select name from sysobjects o, syscomments s where o.id = s.id and text like ...
- php字符串转数组
下面代码包括了含有中文汉字的字符. function str2arr($str) { $length = mb_strlen($str, 'utf-8'); $array = []; for ($i= ...
- cocso引擎整体流程
任何程序都有入口,mian.cpp; Cocos2d也不免俗,在win32平台下,有一个mian.cpp 入口,从这里进入cocos的世界. #ifndef __MAIN_H__ #define __ ...
- day13 内置函数一
见如下网址 https://www.processon.com/mindmap/5bdc3f49e4b0844e0bc6b5d3
- debian系linux墙内安装安全工具集
虽然有kali linux这样集合了很多安全工具的操作系统,但是kali的软件源相对老旧,没有ubuntu等主流debian系统丰富,kali默认使用su权限进入图形化界面也是违背linux权限机制的 ...
- JAVA EE------XML
1.XML定义:在电子计算机中,标记指计算机所能理解的信息符号,通过此种标记,计算机之间可以处理包含各种的信息比如文章等.它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语 ...
- 查找数组中重复的唯一元素+时间复杂度O(n)+空间复杂度O(1)
这是我BIGO前端面试时,面试官给我出的一道题,题目是长度为N的数组,元素大小范围在[1,N-1],只有一个重复的元素,用O(n)的时间复杂度和O(1)的空间复杂度找出来这个重复的元素, 大致思路 1 ...
- code about led_shake
//write by:cyt //Project Name:Led on/off //Time:2017-2-10 #include<reg51.h> void delay(int c) ...
- amazeUI的confirm控件记录缓存问题的解决办法
场景:列表行每行都有删除按钮,点击删除按钮将行记录的id传给js方法,js方法中调用amazeui的confirm控件,确认删除function通过ajax执行删除行为. 问题现象:每次删除列表第一行 ...