|
3 | 3 | * @return {number} |
4 | 4 | */ |
5 | 5 |
|
6 | | -var twoSum = function(nums, target) { // Find two numbers which are two-sum of target in nums |
7 | | - const map = new Map(); // create a new map |
8 | | - for (let i in nums){ // now iterate over nums |
9 | | - const complement = target - nums[i] // find complement of target to current |
10 | | - if (map.has(complement)){ // if there's complement in map |
11 | | - return [map.get(complement), i] // return complement and current index |
| 6 | +var twoSum = function (nums, target) { // Find two numbers which are two-sum of target in nums |
| 7 | + const map = new Map(); // create a new map |
| 8 | + for (let i = 0; i < nums.length; i++) { // now iterate over nums |
| 9 | + const complement = target - nums[i] // find complement of target to current |
| 10 | + if (map.has(complement)) { // if there's complement in map |
| 11 | + return [map.get(complement), i] // return complement and current index |
12 | 12 | } |
13 | | - map.set(nums[i], i) // map current number to current index otherwise |
| 13 | + map.set(nums[i], i) // map current number to current index otherwise |
14 | 14 | } |
15 | | -}; |
| 15 | +}; |
16 | 16 |
|
17 | | -var missingNumber = function(nums) { |
| 17 | +var searchMatrix = function (matrix, target) { |
| 18 | + if (!matrix.length || !matrix[0].length) return false; |
| 19 | + let row = 0; |
| 20 | + let col = matrix[0].length - 1; |
| 21 | + while (row < matrix.length && col >= 0) { |
| 22 | + if (matrix[row][col] === target) { |
| 23 | + return true; |
| 24 | + } else if (matrix[row][col] > target) { |
| 25 | + col-- |
| 26 | + } else row++ |
| 27 | + } |
| 28 | + return false |
| 29 | +}; |
| 30 | + |
| 31 | +var missingNumber = function (nums) { |
18 | 32 | const n = nums.length; |
19 | | - const expextedSum = (n*(n+1))/2; |
20 | | - const actualSum = nums.reduce((sum, num)=>num+sum, 0) |
21 | | - return expextedSum-actualSum; |
| 33 | + const expextedSum = (n * (n + 1)) / 2; |
| 34 | + const actualSum = nums.reduce((sum, num) => num + sum, 0) |
| 35 | + return expextedSum - actualSum; |
22 | 36 | }; |
23 | 37 |
|
24 | 38 | function singleNumber(nums) { |
25 | 39 | let unique = 0; |
26 | 40 | for (let num of nums) { |
27 | | - unique ^= num; // XOR each number |
| 41 | + unique ^= num; // XOR each number |
28 | 42 | } |
29 | 43 | return unique; |
30 | 44 | } |
31 | 45 |
|
32 | 46 | function moveZeroes(nums) { |
33 | 47 | let lastNonZeroIndex = 0; |
34 | | - |
| 48 | + |
35 | 49 | // Move all non-zero elements to the front |
36 | 50 | for (let i = 0; i < nums.length; i++) { |
37 | 51 | if (nums[i] !== 0) { |
|
0 commit comments