美文网首页
剑指 Offer 57. 和为s的两个数字

剑指 Offer 57. 和为s的两个数字

作者: 邦_ | 来源:发表于2022-03-09 10:02 被阅读0次

想着用个双指针,左右两个往中间移动,发现时间上还是特别长。。

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
       var tempRight = nums.count - 1
        var tempLeft = 0
        var array = [Int]()
        
        while tempLeft < tempRight {
           
            if nums[tempRight] > target {
                tempRight -= 1
                continue
            }
            if nums[tempLeft] + nums[tempRight] == target {
                
                array.append(nums[tempLeft])
                array.append(nums[tempRight])
                break
                
            }
          
            if nums[tempLeft] + nums[tempRight] > target {
                tempRight -= 1
            }
            else
            {
                tempLeft += 1
            }
          
        }
      
        return array
    }

看了官方的算法。。 提交之后还不如上边的= = 困惑了


func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
      var tempRight = nums.count - 1
        var tempLeft = 0
        var array = [Int]()
        
        while tempLeft < tempRight {
            
            let s = nums[tempLeft] + nums[tempRight]
        
            if  s > target {
                tempRight -= 1
            }
            else if s < target
            {
                tempLeft += 1
            }
            else {
                
                array.append(nums[tempLeft])
                array.append(nums[tempRight])
                break
            }
           
        }
        
        
        return array
    }








相关文章

网友评论

      本文标题:剑指 Offer 57. 和为s的两个数字

      本文链接:https://www.haomeiwen.com/subject/awcnrrtx.html