【leetcode】1. two sum两数之和

leetcode(1): two sum

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:


Given nums = [2, 7, 11, 15], target = 9,



Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

0. My solution(Brute Force)


var twoSum = function(nums, target) {

    for(let i = 0; i < nums.length; i++) {

        for(let j = 0; j < nums.length; j++) {

            if(nums[i] + nums[j] === target && i != j) {

                return [i, j]

            }

        }

    }

};

· Time complexity: O(n^2), For each element, I try to find its complement by looping through the rest of array which takes O(n)*O(n) time. Therefore, the time complexity is O(n^2).

📅 2020-01-15

js类似于printf那样的格式化字符串

安装包


npm install sprintf-js

调用包


var sprintf = require('sprintf-js').sprintf,

操作实例:时间前补零操作


for (let i = 46; i >= 0; i--) {

        console.log(sprintf('%2d:%02d', i / 2, (i % 2 ? 0 : 30)))

      }
📅 2019-03-13