• leetcode-两数之和


    题目:两数之和

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

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

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

    示例 1:

    输入:nums = [2,7,11,15], target = 9
    输出:[0,1]
    解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
    • 第一次提交没有考虑到同一个元素相加 等于 tager

    • 第二次提交没有考虑到数组元素为负数

     

    • 提交通过,不过时间复杂度为O(n^2)
     1 class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         int[] array = new int[2];
     4         b:for(int i = 0;i<nums.length ; i++){
     5                 for(int j =0;j<nums.length;j++){
     6                     if(i != j && nums[i] + nums[j] == target){
     7                         array[0] = i;
     8                         array[1] = j;
     9                        break b;
    10                     }
    11                 }
    12             
    13         }
    14      return array;
    15     }
    16 }
    • 使用HashMap 时间复杂度 为O(n):我还是觉得双层循环效率更高一些
     1 class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         int[] array = new int[2];
     4         Map<Integer,Integer> map = new HashMap<>();
     5         for(int i = 0;i<nums.length ; i++){
     6             if(!map.containsKey(target-nums[i])){
     7                 map.put(nums[i],i);
     8             } else{
     9                 array[0] = map.get(target - nums[i]);
    10                 array[1] = i;
    11             }
    12             
    13         }
    14         return array;
    15     }
    16 }
  • 相关阅读:
    Python设计模式
    Python设计模式
    Python设计模式
    Python设计模式
    Python设计模式
    Python设计模式
    Python设计模式
    Python设计模式
    composer安装以及更新问题,配置中国镜像源。
    PHP使用文件排它锁,应对小型并发
  • 原文地址:https://www.cnblogs.com/kingxiaozi/p/14347351.html
Copyright © 2020-2023  润新知