博客
关于我
两数之和
阅读量:550 次
发布时间:2019-03-09

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

一、LeetCode之两数之和 

public class TwoSum {    /**     * 通过双重循环遍历数组中所有元素的两两组合     * 当出现符合的和时返回两个元素的下标     * @param nums     * @param target     * @return     */    public static int[] twoSum1(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j< nums.length; j++) {                if (target - nums[i] == nums[j]) {                    return new int[]{i, j};                }            }        }        return null;    }    //哈希    public static int[] twoSum2(int[] nums, int target) {        HashMap
map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int partnerNumber = target - nums[i]; if (map.containsKey(partnerNumber)) { return new int[]{map.get(partnerNumber), i}; } map.put(nums[i], i); //map K值 V下标 // 2 0 } return null; } public static void main(String[] args) { int[] nums = new int[]{2, 7, 11, 15}; int target = 22; int[] myIndex = twoSum2(nums, target); System.out.println(Arrays.toString(myIndex)); }}

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

你可能感兴趣的文章
mysql之连接查询,多表连接
查看>>
mysql乐观锁总结和实践 - 青葱岁月 - ITeye博客
查看>>
mysql也能注册到eureka_SpringCloud如何向Eureka中进行注册微服务-百度经验
查看>>
mysql乱码
查看>>
Mysql事务。开启事务、脏读、不可重复读、幻读、隔离级别
查看>>
MySQL事务与锁详解
查看>>
MySQL事务原理以及MVCC详解
查看>>
MySQL事务及其特性与锁机制
查看>>
mysql事务理解
查看>>
MySQL事务详解结合MVCC机制的理解
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
webpack css文件处理
查看>>
mysql二进制包安装和遇到的问题
查看>>
MySql二进制日志的应用及恢復
查看>>
mysql互换表中两列数据方法
查看>>
mysql五补充部分:SQL逻辑查询语句执行顺序
查看>>
mysql交互式连接&非交互式连接
查看>>
MySQL什么情况下会导致索引失效
查看>>
Mysql什么时候建索引
查看>>