167. Two Sum II - Input array is sorted - LeetCode
2024-10-20 16:08:22
Question
167. Two Sum II - Input array is sorted
Solution
题目大意:和Two Sum一样,这里给出的数组是有序的
思路:target - nums[i],这样就实现了降维了
Java实现:
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i + 1;
result[0] = map.get(target - nums[i]) + 1;
return result;
}
map.put(nums[i], i);
}
return result;
}
别人的实现:
public int[] twoSum(int[] num, int target) {
int[] indice = new int[2];
if (num == null || num.length < 2) return indice;
int left = 0, right = num.length - 1;
while (left < right) {
int v = num[left] + num[right];
if (v == target) {
indice[0] = left + 1;
indice[1] = right + 1;
break;
} else if (v > target) {
right --;
} else {
left ++;
}
}
return indice;
}
最新文章
- iOS 升级HTTPS通过ATS你所要知道的
- ABP 索引
- CSS手动改变DIV高宽
- SP2-0618: 无法找到会话标识符。启用检查 PLUSTRACE 角色 SP2-0611: 启用 STATISTICS 报告时出错
- Linux shell相关
- Web UI自动化测试中绕开验证码登陆方式浅谈
- iOS 蓝牙开发(二)iOS 连接外设的代码实现(转)
- SQL脚本书写的几点建议
- LightOJ1018 Brush (IV)(状压DP)
- JTAG
- Python元组(tuple)
- Verilog如何从外部更改模块内参数
- ICAO 附件十四面课件分享
- Easy-UI开发总结
- HTML5学习笔记简明版(8):新增的全局属性
- [Javascript] Understand Curry
- VMware安装的Windows10下Docker的安装
- sift算法特征点如何匹配?
- Android 调整图标和字体大小
- 关于JAVA中Byte数据类型二进制赋值运算报错问题