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 ...
随机推荐
- 练习 HashSet 去重复
package com.rf.xs.list; import java.util.HashSet; public class Person { private String name; private ...
- windows分驱
步骤/方法 1 鼠标右击“计算机” 2 选择“管理”标签 3 打开“计算机管理”窗口 选择“磁盘“>>”存储管理“,打开”磁盘管理“页面 如图: 右键单击选择要压缩的磁盘(本例 ...
- [工控安全]“祝融”—一种针对PLC控制系统的欺骗攻击病毒
“祝融”作为一种针对传统PLC控制系统的欺骗攻击病毒,所述的典型的PLC控制系统通常包括两部分: 用于组态.编程.监视.控制的工程师站(通常是PC设备) PLC控制器(通常如西门子.施耐德.三菱等厂家 ...
- Adversarial Examples for Semantic Segmentation and Object Detection 阅读笔记
Adversarial Examples for Semantic Segmentation and Object Detection (语义分割和目标检测中的对抗样本) 作者:Cihang Xie, ...
- Python PIL
Python PIL PIL (Python Image Library) 库是Python 语言的一个第三方库,PIL库支持图像存储.显示和处理,能够处理几乎所有格式的图片. 一.PIL库简介 1. ...
- vue项目中,使用vue-awesome-swiper插件实现轮播图
一.安装 npm install vue-awesome-swiper 二.项目中引入 import 'swiper/dist/css/swiper.css'import {swiper,swiper ...
- My SQL随记 003 数据表基础操作语法
数据表 查看数据表 修改表名 修改字段名 修改字段数据类型 添加删除-字段 约束(主外键默认检查) 查看表结构: 语法:DESRIBE(描述) table_Name; DESC table_Name ...
- c++ cin cin.getline() getline()用法
http://www.cnblogs.com/AndyJee/p/3821067.html 主要内容: 1.cin用法 2.cin.getline()用法 3.getline()用法 3.注意的问题 ...
- Spring Boot 异步运用
使用@Async标签 导入包 org.springframework.scheduling.annotation.Async 并配置并发线程池asyncTaskConfig 实现AsyncConfig ...
- Date对象方法
创建Date new Date() Date对象方法: get系列: getDate() 返回一个月中的某一天(1-31) getDay() ...