博客
关于我
两数之和
阅读量: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中的ON DUPLICATE KEY UPDATE详解与应用
查看>>
mysql中的rbs,SharePoint RBS:即使启用了RBS,内容数据库也在不断增长
查看>>
mysql中的undo log、redo log 、binlog大致概要
查看>>
Mysql中的using
查看>>
MySQL中的关键字深入比较:UNION vs UNION ALL
查看>>
Mysql主从不同步
查看>>
mysql主从同步及清除信息
查看>>
MySQL主从篇:死磕主从复制中数据同步原理与优化
查看>>
mysql主从配置
查看>>
MySQL之2003-Can‘t connect to MySQL server on ‘localhost‘(10038)的解决办法
查看>>
MySQL之DML
查看>>
mysql之分组查询GROUP BY,HAVING
查看>>
mysql之分页查询
查看>>
mysql之子查询
查看>>
MySQL之字符串函数
查看>>
Mysql之性能优化--索引的使用
查看>>
mysql之旅【第一篇】
查看>>
Mysql之索引选择及优化
查看>>
mysql之联合查询UNION
查看>>
mysql乱码
查看>>