It's the Xinrui Ma

Blog

Tag: Two Pointers

Remove Nth Node From End of List

Posted by in LeetCode on

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Solution:

Linked List Cycle II Go to Discuss

Posted by in LeetCode on

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

Solution in JavaScript:

11. Container With Most Water

Posted by in LeetCode on

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

We can start from the most width to least width:

Brute Force Solution:

Better Two Pointer Solutio: (Start from the longest width, then move the short line pointer inner towards higher line):

88. Merge Sorted Array

Posted by in LeetCode on

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Hint: IWhat if you fill the longer array from the end instead of start?

350. Intersection of Two Arrays II — LeetCode

Posted by in LeetCode on

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Solution1: Hashtable
Count how many times each digit appears in nums1, store in hash table, where key is the number in array, value is the times.
Then iterate through nums2 array, if the number in nums2 is key of the hashtable, then check if the value larger then 1, if yes, store that number to result array.