博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1. Two Sum
阅读量:2352 次
发布时间:2019-05-10

本文共 1522 字,大约阅读时间需要 5 分钟。

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

我的思路

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2]; if(nums == null || nums.length <= 1) return res; HashMap
map = new HashMap
(); for(int i = 0; i < nums.length; i++){
int val = target - nums[i]; if(map.containsKey(val) && map.get(val) != i){
res[0] = i; res[1] = map.get(val); return res; }else map.put(nums[i], i); } return res; }}

2019.12.17 update:

因为结果与index无关,可以对原数组先排序,再用双指针。
空间复杂度为O(1),时间复杂度为O(nlogn)。不过这个方法为何时间复杂度是nlogn我还是没有太想清楚

public class Solution {
public int[] twoSum(int[] numbers, int target) {
Arrays.sort(numbers); int L = 0, R = numbers.length - 1; while (L < R) {
if (numbers[L] + numbers[R] == target) {
int[] pair = new int[2]; pair[0] = numbers[L]; pair[1] = numbers[R]; return pair; } if (numbers[L] + numbers[R] < target) {
L++; } else {
R--; } } return null; }}

转载地址:http://qyqvb.baihongyu.com/

你可能感兴趣的文章
Zookeeper
查看>>
更新mysql5.7修改字符集
查看>>
Windows系统护眼色设置
查看>>
JUC多线程&lambda之美&ThreadLocal
查看>>
碎片清理
查看>>
程序员不能错过的技术网站
查看>>
冒泡排序(分析+代码调优)
查看>>
Vue
查看>>
乐优商城总结
查看>>
如何使用Git上传和更新项目至Github
查看>>
选择排序(分析+代码调优)
查看>>
Docker
查看>>
代码优化建议,44条代码优化细节
查看>>
快速排序(图解分析+代码调优)
查看>>
Java基础面试总结
查看>>
HashMap遍历几种方式比较(传统的Map迭代方式对比JDK8的迭代方式)
查看>>
Java面试& HashMap实现原理分析
查看>>
PS修改动图字幕
查看>>
八大基础排序总结
查看>>
Linux下安装使用FastDFS
查看>>