Two Sum
来源:互联网 发布:手机拨打电话软件 编辑:程序博客网 时间:2024/06/05 23:52
问题描述:对于一个整数数组,给定一个值target,找出数组中两个元素和为target并返回这两个元素下标组成的数组。
解决:使用,存储的键为numsi,值为i.每次从nums数组中拿到一个值a去map中查找是否有targeta这个键。这样的方式时间复杂度为on。
/* * 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 */class A1 { public int[] twoSum(int[] nums, int target) { int[] rtn = new int[2]; if(nums == null || nums.length<2) { return null; } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length); for(int i=0; i<nums.length; i++) { if(map.containsKey(target-nums[i])) { rtn[0] = map.get(target-nums[i]); rtn[1] = i; return rtn; } map.put(nums[i], i); } return null; }}
阅读全文
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Entity Framework学习笔记(初学)
- 多线程的三种建立方式
- Linux命令之 chgrp,chmod,chown
- JAVA Scanner的用法
- 加载RT3070驱动出现 Unknown symbol led_classdev_suspend的解决方法
- Two Sum
- 简单优化后的无限轮播+listview,没有小圆点
- JSP 标准标签库(JSTL)
- 信用货币创造和派生的原理
- DirectX11 初始化(2) 框架搭建
- 上拉加载,下拉刷新,xlistview
- Tcp协议学习
- C#实现AOP框架
- 神经网络与深度学习学习笔记:向量化与for循环对比