1. Two Sum
来源:互联网 发布:身份证恶搞软件 编辑:程序博客网 时间:2024/06/03 19:40
题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
想法
对nums建立hash表,再遍历nums,看hash表中有没有相对应的关键字加上num会等与target
代码int* twoSum(int* nums, int numsSize, int target) { int min = nums[ 0 ], max = nums[ 0 ]; int *arr = malloc( sizeof( int ) * 2 ); for( int i = 1; i < numsSize; i++ ) { if( min > nums[ i ] ) { min = nums[ i ]; } if( max < nums[ i ] ) { max = nums[ i ]; } } int *hash = malloc( sizeof( int ) * ( max - min + 1 ) ); for( int i = 0; i < max - min + 1; i++ ) { hash[ i ] = -1; } for( int i = 0; i < numsSize; i++ ) { int key = target - nums[ i ] - min; if( key < 0 || key >= max - min + 1) { continue; } if( hash[ key ] >= 0 ) { arr[ 0 ] = i; arr[ 1 ] = hash[ key ]; free( hash ); return arr; } hash[ nums[ i ] - min ] = i; } free( hash ); return arr;}
1 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- Java多线程:线程状态
- poj3213(特殊的矩阵乘法)
- 下一个风口就是硬科技,抓住机遇,中国能重返世界之巅
- Web AppBuilder for ArcGIS(开发版)系列教程 1
- MyBatis Generator 通过xml生成,有日志但是没有生成文件成功的问题
- 1. Two Sum
- windows 7 composer的安装
- 不要在linux上启用net.ipv4.tcp_tw_recycle参数
- 机器学习--knn手写数字识别系统
- 硬科技改变世界
- js设置cookie
- 微分方程的数值解法——常微分方程——欧拉法与改进欧拉法(2)
- c/c++整理--位运算与嵌入式编程(1)
- 递推——Codeforces 319A