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]
        }
    }
  • 相关阅读:
    php设计模式-工厂模式(一)
    php Pthread 线程 互斥锁
    php Pthread 多线程 Worker
    PHP多进程实例
    C# this 关键字
    .NET FileStream文件流,StreamReader文本流,MemoryStream内存流几种流的实例
    深入理解Static关键字修饰符
    SQL Server 视图
    .NET初识委托
    RSA加密
  • 原文地址:https://www.cnblogs.com/kaisi/p/10112252.html
Copyright © 2011-2022 走看看