LeetCode one Two Sum (JAVA)

简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数.

问题详解:

给定一个数据类型为int的数组,一个数据类型为int的目标值target,要求是在数组中寻求两个数字,使得两个数求和的值等于给定的target,要求以数组返回符合条件的索引.

技巧:可以假设数组中没有重复元素,因为我们只返回一个符合条件的数组,所以数组中只需要一个符合要求的数字就可以了.

举例:

给定数组 nums={5,8,7,2,11},target= 10,

因为nums[1]+nums[3]=8+2=10,

所以返回[1,3].

注意:

1.数组下标不能重复

错解:nums[0]+nums[0]=5+5=10,

返回[0,0].

2.要考虑到没有符合的结果时的处理.

JAVA实现方法一:暴力遍历,两层循环,不推荐(第一次愚蠢实现)

public int[] twoSum(int[] nums, int target) {

for (int i = 0; i < nums.length; i++) {

for (int j = i + 1; j < nums.length; j++) {

if (nums[j] == target - nums[i]) {

return new int[] { i, j };

}

}

}

throw new IllegalArgumentException("No two sum solution");

}

学习之路:

官方实现一 : 双层遍历.

优点:

1.代码的简洁性.

2.用throw方法处理无结果.

public int[] twoSum(int[] nums, int target) {

Map<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < nums.length; i++) {//存放数组数据

map.put(nums[i], i);

}

for (int i = 0; i < nums.length; i++) {//判断结果

int complement = target - nums[i];

if (map.containsKey(complement) && map.get(complement) != i) {

return new int[] { i, map.get(complement) };

}

}

throw new IllegalArgumentException("No two sum solution");

}

复杂度分析:

时间复杂度 :近似于O(n^2):双层遍历,方法执行了n*n次.

空间复杂度 :近似于 O(1):变量的定义为常数.

官方实现二 : 利用HashMap两次遍历

先存放数组数据,再判断Map数据.

优点:

1.利用Hash表通过空间交换时间的方法提高查找时间.

2.因为不需要两个重复的数字,所以不会与Map中键的特性冲突.

public int[] twoSum(int[] nums, int target) {

Map<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < nums.length; i++) {//存放数组数据

map.put(nums[i], i);

}

for (int i = 0; i < nums.length; i++) {//判断结果

int complement = target - nums[i];

if (map.containsKey(complement) && map.get(complement) != i) {

return new int[] { i, map.get(complement) };

}

}

throw new IllegalArgumentException("No two sum solution");

}

复杂度分析:

时间复杂度 :近似于O(n):都是单层遍历,方法执行了n次.

空间复杂度 :近似于 O(n):一次遍历,变量定义了n次.

LeetCode官方实现三 : 利用HashMap两次遍历

在存放数据的过程中判断结果.

优点:

1.提高了代码的简洁性

public int[] twoSum(int[] nums, int target) {

Map<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < nums.length; i++) {

int complement = target - nums[i];

if (map.containsKey(complement)) {//满足条件直接返回结果,不继续遍历存数据

return new int[] { map.get(complement), i };

}

map.put(nums[i], i);

}

throw new IllegalArgumentException("No two sum solution");

}

复杂度分析:

时间复杂度 :近似于O(n):一次遍历,方法执行了n次.

空间复杂度 :近似于 O(n):一次遍历,变量定义了n次.

随记:

length——数组的属性;

length()——String的方法;

size()——集合的方法;

put()——Map的添加方法 ;

add()——Collection的添加方法;

小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海

LeetCode one Two Sum的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. [leetCode][013] Two Sum 2

    题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...

  4. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  7. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  8. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  9. [LeetCode] 437. Path Sum III_ Easy tag: DFS

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

随机推荐

  1. linux proc

    /proc文件系统下的多种文件提供的系统信息不是针对某个特定进程的,而是能够在整个系统范围的上下文中使用.可以使用的文件随系统配置的变化而变化. /proc/cmdline 这个文件给出了内核启动的命 ...

  2. jquery validate 详解二

    原文:http://blog.sina.com.cn/s/blog_608475eb0100h3h2.html 这里只是第二篇,前面的内容请参阅上一篇 五.常用方法及注意问题 1.用其他方式替代默认的 ...

  3. Nlog日志组件简介

    NLog简介 NLog是一个简单灵活的.NET日志记录类库,NLog的API非常类似于log4net,配置方式非常简单.支持多种形式输出日志:文本文件.系统日志.数据库.控制台.邮箱等 1.NLog简 ...

  4. Sqlserver中的触发器

    一 什么是触发器 1.1  触发器的概念   触发器(trigger)是SQL server来保证数据完整性的一种方法,它是与表事件相关的特殊的存储过程,它的执行是由事件来触发,当对一个表进行操作(  ...

  5. redis使用问题一:Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool] with root cause

    本文使用的是spring-data-redis 首先说下redis最简单得使用,除去配置. 需要在你要使用得缓存得地方,例如mybatis在mapper.xml中加入: <cache evict ...

  6. Django之组件--cookie与session

    cookie组件 cookie:由服务器产生,存放在客户端浏览器上的键值对. 使用: -设置值: obj=HttpResponse('ok') obj.set_cookie('key','value' ...

  7. 【leetcode-75】 颜色分类

    (1过,解法不好,看參考荷兰国旗问题解法) 给定一个包含红色.白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色.白色.蓝色顺序排列. 此题中,我们使用整数 0 ...

  8. 【十四】jvm 性能调优实例

    实例1: POI Excel 导出 Excel对象很大,多人同时登录系统导出Excel的话,就会有多个大Excel对象到老年代,这是老年代需要回收,系统可能会卡顿. jvm堆内存设置的越大,Full ...

  9. daemon_inetd函数

    #include <syslog.h> extern int daemon_proc; /* defined in error.c */ void daemon_inetd(const c ...

  10. JS面向对象的程序设计之理解对象

    一.对象定义 (1)ECMAScript中没有类的概念,因此它的对象也与基于类的语言中的对象有所不同: (2)ECMA-262把对象定义为:“无序属性的集合,其属性可以包含基本值.对象或者函数” 二. ...