博客
关于我
两数之和
阅读量: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执行计划 EXPLAIN参数
查看>>
MySQL执行计划【explain】,看这一篇就够啦!
查看>>
Mysql执行计划字段解释
查看>>
mysql执行计划怎么看
查看>>
MySQL执行计划解读
查看>>
mysql执行顺序与索引算法
查看>>
mysql批量update优化_Mysql中,21个写SQL的好习惯,你值得拥有呀
查看>>
mysql批量update操作时出现锁表
查看>>
MYSQL批量UPDATE的两种方式
查看>>
mysql批量修改字段名(列名)
查看>>
MySQL批量插入数据遇到错误1213的解决方法
查看>>
mysql技能梳理
查看>>
MySQL报Got an error reading communication packets错
查看>>
Mysql报错Can‘t create/write to file ‘/tmp/#sql_3a8_0.MYD‘ (Errcode: 28 - No space left on device)
查看>>
MySql报错Deadlock found when trying to get lock; try restarting transaction 的问题解决
查看>>
MySQL报错ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘
查看>>
Mysql报错Packet for query is too large问题解决
查看>>
mysql报错级别_更改MySQL日志错误级别记录非法登陆(Access denied)
查看>>
Mysql报错:too many connections
查看>>