博客
关于我
两数之和
阅读量: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事务原理以及MVCC详解
查看>>
MySQL事务及其特性与锁机制
查看>>
mysql事务理解
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
mysql交互式连接&非交互式连接
查看>>
MySQL什么情况下会导致索引失效
查看>>
MySql从入门到精通
查看>>
MYSQL从入门到精通(二)
查看>>
mysql以服务方式运行
查看>>
mysql优化--索引原理
查看>>
MySQL优化配置详解
查看>>
mysql会员求积分_MySql-统计所有会员的最高前10次的积分和
查看>>
MySQL修改密码报错ERROR 1396 (HY000): Operation ALTER USER failed for ‘root‘@‘localhost‘
查看>>
Mysql全局优化参数
查看>>
MySQL全面瓦解:安装部署与准备
查看>>
MySQL内存表使用技巧
查看>>
MySQL函数
查看>>
mysql函数汇总之数学函数
查看>>
mysql函数汇总之条件判断函数
查看>>