LeetCode----Two Sum
2016-09-14 15:29
399 查看
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.
Example:
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; for (int i = 0; i < numbers.length; i++) { if (map.containsKey(numbers[i])) { int index = map.get(numbers[i]); result[0] = index ; result[1] = i; break; } else { map.put(target - numbers[i], i); } } return result; } }
int* twoSum(int* nums, int numsSize, int target) { int min = 2147483647; int i = 0; for (i = 0; i < numsSize; i++) { if (nums[i] < min) min = nums[i]; } int max = target - min; int len = max - min + 1; //确定hash长度 int *table = (int*)malloc(len*sizeof(int)); int *indice = (int*)malloc(2*sizeof(int)); for (i = 0; i < len; i++) { table[i] = -1; //hash初值 } for (i = 0; i < numsSize; i++) { if (nums[i]-min < len) { if (table[target-nums[i]-min] != -1) { //满足相加为target indice[0] = table[target-nums[i] - min]; indice[1] = i; return indice; } table[nums[i]-min] = i; } } free(table); return indice; }
相关文章推荐
- MySQL Blob类型简介
- 40、Drools语法篇之Global全局变量
- Android中的原生和 H5
- RDD基本转换操作(5)–mapPartitions、mapPartitionsWithIndex
- 关于时钟频率和带宽
- Java jdbc批量多线程读取CVS文件入库性能优化篇
- ThinkPHP中session函数详解
- spark-shell学习笔记
- scala 学习笔记
- NO.168 如何做禅道二次开发(4):如何登记菜单
- 热更新--android与lua相互通信++++++++what
- 【SpringMVC学习07】SpringMVC中的统一异常处理
- 题目15:链表中倒数第K个结点
- Apache配置支持目录浏览
- 从JKS文件中读取密钥
- 单例模式的简单使用(QML调用C++)
- php获取服务器操作系统等信息
- 回车键实现按钮点击事件
- listview简单实现多选
- RDD基本转换操作(4)–union、intersection、subtract