diff --git a/solution/0001.Two Sum/Solution3.js b/solution/0001.Two Sum/Solution3.js new file mode 100644 index 0000000000000..088769f771031 --- /dev/null +++ b/solution/0001.Two Sum/Solution3.js @@ -0,0 +1,9 @@ +var twoSum = function(nums, target) { + const map = new Map() + for(let i = 0; i < nums.length; i++){ + if (map.has(target - nums[i])){ + return [ map.get(target - nums[i]), i ] + } + map.set(nums[i], i) + } +}; \ No newline at end of file diff --git a/solution/0002.Add Two Numbers/Solution2.js b/solution/0002.Add Two Numbers/Solution2.js new file mode 100644 index 0000000000000..2d488981100a1 --- /dev/null +++ b/solution/0002.Add Two Numbers/Solution2.js @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + let head = new ListNode(0) + let cur = head + let curry = 0 + + while (true) { + let sum = curry + sum += l1 ? l1.val : 0 + sum += l2 ? l2.val : 0 + cur.val = sum % 10 + curry = parseInt(sum / 10) + if (l1) l1 = l1.next + if (l2) l2 = l2.next + if (l1 != null || l2 != null) { + cur.next = new ListNode(0) + cur = cur.next + } else { + break + } + } + if (curry != 0) { + cur.next = new ListNode(0) + cur = cur.next + cur.val = curry + } + return head + }; + + var l1 = new ListNode(1) + l1.next = new ListNode(8) + + var l2 = new ListNode(0) + + console.log(addTwoNumbers(l1, l2)) \ No newline at end of file diff --git a/solution/0003.Longest Substring Without Repeating Characters/Solution.js b/solution/0003.Longest Substring Without Repeating Characters/Solution.js new file mode 100644 index 0000000000000..d63cafcb8e123 --- /dev/null +++ b/solution/0003.Longest Substring Without Repeating Characters/Solution.js @@ -0,0 +1,22 @@ +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + var start = 0; // 非重复字符串开始索引 + var max = 0; // 最长字符串长度 + var visitedCharByPosition = {}; + for (var position = 0; position < s.length; position++) { + var nextChar = s[position]; + if (nextChar in visitedCharByPosition && visitedCharByPosition[nextChar] >= start) { + // 有重复,非重复字符串索引从下一个 index 开始 + start = visitedCharByPosition[nextChar] + 1; + visitedCharByPosition[nextChar] = position; + } else { + visitedCharByPosition[nextChar] = position; + // 非重复,求非重复值 + max = Math.max(max, position + 1 - start); + } + } + return max; +}; \ No newline at end of file