LeetCode
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2)
time complexity?
Solutions:
a.Brute force solution:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if (nums[i] + nums[j]) == target:
return [i,j]
b. Using HashMap
class Solution:
# This function finds two numbers in the 'nums' list that add up to the 'target' value.
# It returns a list containing the indices of the two numbers.
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Initialize an empty hashmap to store the values and their corresponding indices
hashmap = {}
# Iterate through the 'nums' list using indices
for i in range(len(nums)):
# Calculate the complement of the current number
complement = target - nums[i]
# If the complement exists in the hashmap
if complement in hashmap:
# Return the indices of the complement and the current number
return [hashmap[complement], i]
# Add the current number and its index to the hashmap
hashmap[nums[i]] = i
9. Palindrome Number easy
Given an integer x
, return true
if x
is a
, and false
otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
Solutions:
a. Convert Integer to String:
class Solution:
def isPalindrome(self, x: int) -> bool:
str_x = str(x)
len_x = len(str_x)
for i in range(len_x):
if str_x[i] != str_x[len_x-i-1]:
return False
return True
or
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]
b. Dont't Convert Integer to String:
class Solution:
# This function checks if a given integer is a palindrome.
def isPalindrome(self, x: int) -> bool:
# Check if the number is negative or a multiple of 10 (excluding 0)
if x < 0 or (x != 0 and x % 10 == 0):
return False
reversed_num = 0
original = x
# Reverse the second half of the number
while x > reversed_num:
reversed_num = reversed_num * 10 + x % 10 # Add the last digit of 'x' to 'reversed_num'
x //= 10 # Remove the last digit of 'x'
# Check if the reversed number matches the original number, x == reversed_num // 10 is when X have odd width
return x == reversed_num or x == reversed_num // 10
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
Solutions:
class Solution(object):
# This function merges two sorted linked lists into a single sorted linked list.
# It takes two non-reduced sequences 'list1' and 'list2' as input.
def mergeTwoLists(self, list1, list2):
# Initialize a new ListNode as the head of the merged list
head = ListNode()
# Initialize a pointer 'current' to traverse the merged list
current = head
# Continue until either list1 or list2 becomes None
while list1 and list2:
# If the value of the current node in list1 is smaller than list2
if list1.val < list2.val:
# Append the current node of list1 to the merged list
current.next = list1
# Move to the next node in list1
list1 = list1.next
else:
# Append the current node of list2 to the merged list
current.next = list2
# Move to the next node in list2
list2 = list2.next
# Move the 'current' pointer to the last appended node
current = current.next
# Connect the remaining nodes of list1 or list2 to the merged list
current.next = list1 or list2
# Return the head of the merged list (excluding the dummy node)
return head.next
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums
.
Consider the number of unique elements of nums
to be k
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the unique elements in the order they were present innums
initially. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.
Solutions:
class Solution(object):
def removeDuplicates(self, nums):
replace = 1
for i in range(1, len(nums)):
if nums[i-1] != nums[i]:
nums[replace] = nums[i]
replace += 1
return replace
An n-bit gray code sequence is a sequence of 2n
integers where:
- Every integer is in the inclusive range
[0, 2n - 1]
, - The first integer is
0
, - An integer appears no more than once in the sequence,
- The binary representation of every pair of adjacent integers differs by exactly one bit, and
- The binary representation of the first and last integers differs by exactly one bit.
Given an integer n
, return any valid n-bit gray code sequence.
Example 1:
Input: n = 2
Output: [0,1,3,2]
Explanation:
The binary representation of [0,1,3,2] is [00,01,11,10].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
Example 2:
Input: n = 1
Output: [0,1]
Constraints:
1 <= n <= 16
Solution:
class Solution:
def grayCode(self, n: int) -> List[int]:
L = [0]
for i in range(1,2**n):
L.append(i^(i>>1))
return L
Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: false
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
for i in range(32):
if 2 ** i == n:
return True
return False
b. bit information pow_n: 100/ 1000/ 10000/ 100000 pow_n - 1 = 011/ 0111/ 01111/ 011111 pow_n & pow_n-1 = 0
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n-1) == 0
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 105
s[i]
is a printable ascii character.
Solutions:
a.
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
str_len = len(s)
for i in range(str_len>>1):
s[i],s[str_len-i-1] = s[str_len-i-1],s[i]
b. we can't directly write s = s[::-1]
,becase it will create a new list,and let s point to zhe new list, but we can write s[:] = s[::-1]
,becasue it guarantees that opreate in original list. or we can write s.revrese()
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:]=s[::-1]