博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode之旅】数组- 1.两数之和
阅读量:2056 次
发布时间:2019-04-28

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

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]
public class SumNum {    public static void main(String[] args) {        int[] arr = {1,3,4,5,6,7,8,11,15};//        int[] result = twoSum1(arr, 12);        int[] result = twoSum2(arr, 13);        for (int i = 0; i < result.length; i++) {            System.out.println(result[i]);        }    }    /**     * 暴力法     * 时间复杂度 O(n^2)     * @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 - i; j++) {                if (nums[j] == target - nums[i]){                    return new int[]{i,j};                }            }        }        throw new IllegalArgumentException("没有满足条件的数");    }    /**     * 一遍哈希表:将数据放入HashMap中     * @param nums     * @param target     * @return     */    public static int[] twoSum2(int[] nums,int target){        Map
map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)){ return new int[]{map.get(complement),i}; } map.put(nums[i],i); } throw new IllegalArgumentException("没有满足条件的数"); }}

 

 

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

你可能感兴趣的文章
教你玩转微服务的装逼指南!
查看>>
Envoy 中文指南系列:Sidecar 模式
查看>>
面试官邪魅一笑:你猜一个 TCP 重置报文的序列号是多少?
查看>>
Envoy 中文指南系列: 安装
查看>>
最华丽的 Kubernetes 桌面客户端:Lens
查看>>
太赞了,这个神器竟然能分分钟将多个 kubeconfig 合并成一个!
查看>>
如何解决容器中 nginx worker process 自动设置的问题
查看>>
ethtool 原理介绍和解决网卡丢包排查思路
查看>>
HPE 推出容器平台 Ezmeral,向 VMware 与 Red Hat 下战书
查看>>
使用 Prometheus-Operator 监控 Calico
查看>>
如果你不习惯新版的 Github 的 UI 界面,可以试试这款插件
查看>>
容器化囧途——没上容器时好好的?
查看>>
linux内核网络参数tcp_tw_recycle 和 tcp_tw_reuse 你搞清楚了吗?
查看>>
40核CPU+80G内存的云资源终终终终终于免费了!
查看>>
Drone开源持续集成工具——Pipeline篇
查看>>
Kubernetes 源码剖析之 WorkQueue 队列 | 文末送书
查看>>
根据 PID 获取容器所在的 Pod 名称
查看>>
JAVA 面试很难吗?Oracle 工程师教你轻松搞定BAT!
查看>>
弹窗!到底谁是幕后黑手?
查看>>
免费分享一个最完美的英语学习素材 Englishpod
查看>>