博客
关于我
两数之和
阅读量: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架构与SQL的执行流程_1
查看>>
MySQL架构与SQL的执行流程_2
查看>>
MySQL架构介绍
查看>>
MySQL架构优化
查看>>
mysql架构简介、及linux版的安装
查看>>
MySQL查看数据库相关信息
查看>>
MySQL查看表结构和表中数据
查看>>
MySQL查询优化:LIMIT 1避免全表扫描
查看>>
MySQL查询优化之索引
查看>>
mysql查询储存过程,函数,触发过程
查看>>
mysql查询总成绩的前3名学生信息
查看>>
mysql查询慢排查
查看>>
MySQL查询报错ERROR:No query specified
查看>>
mysql查询数据库储存数据的占用容量大小
查看>>
MySQL查询数据库所有表名及其注释
查看>>
MySQL查询数据表中数据记录(包括多表查询)
查看>>
MySQL查询结果排序
查看>>
MYSQL查询语句优化
查看>>
mysql查询语句能否让一个字段不显示出来_天天写order by,你知道Mysql底层执行原理吗?
查看>>
MySQL查询语句:揭秘专家秘籍,让你秒变数据库达人!
查看>>