• LeetCode 001:两数之和


    一、题目描述

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

    你可以按任意顺序返回答案

    示例:

    输入:nums = [2,7,11,15], target = 9
    输出:[0,1]
    解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

    二、解题方法

    解法一:暴力

    Java:

    1. class Solution {
    2. public int[] twoSum(int[] nums, int target) {
    3. int n = nums.length;
    4. for (int i = 0; i < n; ++i) {
    5. for (int j = i + 1; j < n; ++j) {
    6. if (nums[i] + nums[j] == target) {
    7. return new int[]{i, j};
    8. }
    9. }
    10. }
    11. return new int[0];
    12. }
    13. }

    时间复杂度:O(N2)

    解法二:哈希表

    Java:

    1. class Solution {
    2. public int[] twoSum(int[] nums, int target) {
    3. Map hash= new HashMap();
    4. for(int i=0;i
    5. if(hash.containsKey(target-nums[i])){
    6. return new int[]{hash.get(target-nums[i]),i};
    7. }
    8. hash.put(nums[i],i);
    9. }
    10. return new int[0];
    11. }
    12. }

    时间复杂度:O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1) 地寻找 target - x。 

  • 相关阅读:
    5.0 Java API
    前端HTML笔记整理
    基于java web的户籍管理系统的设计与实现
    865. 具有所有最深节点的最小子树
    温敏传感器概述
    六、Kafka-Eagle监控
    基于STM32智能环境系统
    ES-Docker部署的ES中安装IK分词器
    30张图说清楚 TCP 协议
    21、ila
  • 原文地址:https://blog.csdn.net/m0_64694079/article/details/132769188