LeetCode-05/10/2020
This is a record of my craking process for Leetcode.
1. Two Sum#
1.1 Problem 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].
1.2 Soulution#
It is very easy to come up with a brute force soulution which Time complex is O(n ^ 2).However, we can use a map structure to record the num and index in the nums we have iteratered. And also, when we check each number, we can find (target - number) in the current map. Then, it will be the solution.
1 | public int[] twoSum(int[] nums, int target) { |
2 Add Two Numbers#
2.1 Problem Description#
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
2.2 Soulution#
This problem is quite similar to merge sort. Hence, in my case, I use the concept the merge sort to generate a new line. In addition, when we calculate the last number, we shuould determine whether it has a carry. In my case, I use a variable called flag to record the carry.
1 | /** |
2 Add Two Numbers#
2.1 Problem Description#
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
2.2 Soulution#
This problem is quite similar to merge sort. Hence, in my case, I use the concept the merge sort to generate a new line. In addition, when we calculate the last number, we shuould determine whether it has a carry. In my case, I use a variable called flag to record the carry.
1 | /** |