1.Two Sum
来源:互联网 发布:淘宝店需要营业执照 编辑:程序博客网 时间:2024/06/07 11:05
Given an array of integers, return indices of the two numbers suchthat they add up to a specific target.
//build hash table by array
int max = Integer.MIN_VALUE;//Integer.MIN_VALUE只是一个初始值,无实际意义
int min = Integer.MAX_VALUE;
for (int num : nums) {
if (max < num) {
max = num;
}
if (min > num) {
min = num;
}
}
if (min > target) {
min = target;
}
if (max < target) {
max = target;
}
//之前都是为了确定所有数据的最大值和最小值,确定一个精确的范围
int start = min - max;
int len = max - start + 1;
//len表示我们需要建立的数组的长度
int[] table = new int[len];
Arrays.fill(table, Integer.MIN_VALUE);//数组数值初始化
for (int i = 0; i < nums.length; i++) {
int idx = nums[i] - start;
int v = table[idx];
if (v != Integer.MIN_VALUE && v != i) {
return new int[] {v, i};
}
table[target - nums[i] - start] = i;
//对于每个数据都会存放进去,存放方式为将下标为对应的数据的数组值
//通过数值的比较,一旦符合要求即返回所需数组
}
return new int[] {0, 0};
}
You may assume that each input would have exactly onesolution.
public int[] twoSum(int[] nums, int target) {//build hash table by array
int max = Integer.MIN_VALUE;//Integer.MIN_VALUE只是一个初始值,无实际意义
int min = Integer.MAX_VALUE;
for (int num : nums) {
if (max < num) {
max = num;
}
if (min > num) {
min = num;
}
}
if (min > target) {
min = target;
}
if (max < target) {
max = target;
}
//之前都是为了确定所有数据的最大值和最小值,确定一个精确的范围
int start = min - max;
int len = max - start + 1;
//len表示我们需要建立的数组的长度
int[] table = new int[len];
Arrays.fill(table, Integer.MIN_VALUE);//数组数值初始化
for (int i = 0; i < nums.length; i++) {
int idx = nums[i] - start;
int v = table[idx];
if (v != Integer.MIN_VALUE && v != i) {
return new int[] {v, i};
}
table[target - nums[i] - start] = i;
//对于每个数据都会存放进去,存放方式为将下标为对应的数据的数组值
//通过数值的比较,一旦符合要求即返回所需数组
}
return new int[] {0, 0};
}
0 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
- OP-TEE笔记之OPTEE__OS文件结构
- 查看oracle表空间
- sqlplus中var和print的使用
- RHEL7密码恢复
- iOS开发网络篇—HTTP协议
- 1.Two Sum
- 彻底解决PHP Session不过期以及SessionId保持不变的问题
- 打印较长的json数据Log
- 高级图像去雾算法的快速实现。
- 33. Search in Rotated Sorted Array
- 1093. Count PAT's (25)
- stat/fstat/lstat函数
- 倒计时CountDownTimer 的是使用
- Swift入门一:记Swift与Oc的一些语言区别