zoukankan      html  css  js  c++  java
  • LeetCode

    要求:

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    优化前 时间复杂度O(n^2)

     1 class Solution {
     2     func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
     3         var indexForNum : Int?
     4         var indexForAnotherNum : Int?
     5         
     6         for (index, value) in nums.enumerated() {
     7             if nums.contains(target - value) {
     8                 
     9                 indexForNum = index
    10                 indexForAnotherNum = nums.firstIndex(of: target - value)!
    11                 
    12                 if indexForAnotherNum == indexForNum {
    13                     continue
    14                 }
    15                 break
    16             }
    17         }
    18         return [indexForNum!,indexForAnotherNum!]
    19     }
    20 }

     优化后

    class Solution {
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            var indexForNum : Int = 0
            var indexForAnotherNum : Int = 0
            var dictionary : [Int : Int] = [:]
            
            for (index, arrValue) in nums.enumerated() {
                if dictionary.values.contains(target - arrValue) {
                    indexForAnotherNum = index
                    for (key,dicValue) in dictionary {
                        if dicValue == target - arrValue {
                            indexForNum = key
                            break
                        }
                    }
                    break
                }
                dictionary.updateValue(arrValue, forKey: index)
            }
            return [indexForNum,indexForAnotherNum]
        }
    }
  • 相关阅读:
    uva11021
    WC2019退役失败记
    北大集训2018垫底记
    NOI后训练记录
    NOI2018垫底记
    NOI前训练记录
    JSOI2018R2游(afo)记
    HNOI(AHOI)2018游记
    JSOI2018R1(九省联考)游(afo)记
    LR 8 Hello 戊戌
  • 原文地址:https://www.cnblogs.com/kaisi/p/10112252.html
Copyright © 2011-2022 走看看