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]
        }
    }
  • 相关阅读:
    [牛客]十二桥问题 解题报告
    [NOIP2017 逛公园] 解题报告
    [JSOI2008]最小生成树计数 解题报告
    类欧几里得算法
    概率与期望题目列表
    [SCOI2008]配对 解题报告
    拦截导弹
    牛客网-约数的个数
    牛客网-成绩排名
    最大连续区间和的算法总结
  • 原文地址:https://www.cnblogs.com/kaisi/p/10112252.html
Copyright © 2011-2022 走看看