LeetCode【1】-Two Sum JAVA
来源:互联网 发布:mac电脑flash过期 编辑:程序博客网 时间:2024/06/07 08:41
题目
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].
方法1
暴力索引,时间复杂度为O(n^2)。
public class TwoSum {/** * 时间复杂度为O(n^2) * @param nums * @param target * @return */public static int []twoSum1(int []nums,int target){ int index1,index2; int []index = new int[]{0,1}; for(int i = 0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++){ if(target ==(nums[i]+nums[j])){ index[0]=i; index[1]=j; return index; } } } return index;}
方法2
使用HashMap来做,首先检验target-nums[i]能否加入到HashMap中,若能,则说明前面的数据没有与第i个字符的组合,当添加不成功,则说明存在符合的组合,记录索引,时间复杂度为O(n)。时间缩短很多
public static int []twoSum2(int []nums,int target){ int []index = new int[]{0,1}; HashMap<Integer, Integer> hm = new HashMap<>(); for(int i=0;i<nums.length;i++){ if(hm.containsKey(target-nums[i])){ index[1] = i; index[0] = hm.get(target-nums[i]); return index; }else { hm.put(nums[i], i); } } return index;}
阅读全文
0 0
- LeetCode 1 Two sum Java
- [leetcode-1]Two Sum(java)
- LeetCode 1 - Two Sum ( JAVA )
- LeetCode【1】-Two Sum JAVA
- leetcode#1-Two Sum-java
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- 【Leetcode】two sum JAVA
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- leetcode:Two Sum 【Java】
- LeetCode|Two Sum-java
- leetcode Two Sum(Java)
- [leetcode NO.1] Two Sum (JAVA)
- LeetCode 1 Two Sum for java
- Leetcode-1 Two Sum(Java) -by zzy
- 【leetcode with java】1 Two Sum
- bootstrap环境搭建两种方法之一
- java学习——java基础(十二)之内存泄漏、内存溢出及JVM内存调优
- Hibernate 缓存机制。
- 递归和非递归方法实现辗转相除法
- 基于CAS的单点登录SSO[3]: 改造cas-overlays-template支持Redis存储Ticket
- LeetCode【1】-Two Sum JAVA
- immutable日常操作之深入API
- 百度地图
- 一个activity中调用另一个activity的界面
- XTUOJ 程序设计实践II-2017(部分)
- Vim下Ctrl+S卡死?
- 【源码剖析】Webbench —— 简洁而优美的压力测试工具
- No setter found for property 'mapperLocation' in class 'org.mybatis.spring.SqlSessionFactoryBean' [c
- tomact详解及应用