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;
}

别人的实现:

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51239/Share-my-java-AC-solution.

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;
}

最新文章

  1. iOS 升级HTTPS通过ATS你所要知道的
  2. ABP 索引
  3. CSS手动改变DIV高宽
  4. SP2-0618: 无法找到会话标识符。启用检查 PLUSTRACE 角色 SP2-0611: 启用 STATISTICS 报告时出错
  5. Linux shell相关
  6. Web UI自动化测试中绕开验证码登陆方式浅谈
  7. iOS 蓝牙开发(二)iOS 连接外设的代码实现(转)
  8. SQL脚本书写的几点建议
  9. LightOJ1018 Brush (IV)(状压DP)
  10. JTAG
  11. Python元组(tuple)
  12. Verilog如何从外部更改模块内参数
  13. ICAO 附件十四面课件分享
  14. Easy-UI开发总结
  15. HTML5学习笔记简明版(8):新增的全局属性
  16. [Javascript] Understand Curry
  17. VMware安装的Windows10下Docker的安装
  18. sift算法特征点如何匹配?
  19. Android 调整图标和字体大小
  20. 关于JAVA中Byte数据类型二进制赋值运算报错问题

热门文章

  1. solr集群搭建,zookeeper集群管理
  2. c语言 相关小知识
  3. SphinxJS——把字符串编码成png图片的超轻量级开源库
  4. 使用Vue2+webpack+Es6快速开发一个移动端项目,封装属于自己的jsonpAPI和手势响应式组件
  5. canvas系列教程03-柱状图项目1
  6. vue在移动端的自适应布局
  7. JS实现列表移动(通过DOM操作select标签)
  8. MySQL 中 SQL语句大全(详细)
  9. JS判断数组中的对象的每一个值不能为空
  10. 将base64转成File文件对象