| 1 | package patterns.java; |
| 2 | |
| 3 | public class TwoPointers { |
| 4 | |
| 5 | public void moveZeroesTwoPointers(int[] nums) { |
| 6 | int left = 0; // Pointer for placing non-zero elements |
| 7 | |
| 8 | // Iterate with right pointer |
| 9 | for (int right = 0; right < nums.length; right++) { |
| 10 | if (nums[right] != 0) { |
| 11 | // Swap elements if right pointer finds a non-zero |
| 12 | int temp = nums[left]; |
| 13 | nums[left] = nums[right]; |
| 14 | nums[right] = temp; |
| 15 | left++; // Move left pointer forward |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | public int maxAreaBruteForce(int[] height) { |
| 21 | int n = height.length; |
| 22 | int maxArea = 0; |
| 23 | |
| 24 | // Check all pairs (i, j) |
| 25 | for (int i = 0; i < n; i++) { |
| 26 | for (int j = i + 1; j < n; j++) { |
| 27 | // Height of the container |
| 28 | int minHeight = Math.min(height[i], height[j]); |
| 29 | int width = j - i; // Distance between lines |
| 30 | int area = minHeight * width; // Compute water contained |
| 31 | |
| 32 | maxArea = Math.max(maxArea, area); // Update max water |
| 33 | } |
| 34 | } |
| 35 | return maxArea; |
| 36 | } |
| 37 | |
| 38 | public int maxAreaTwoPointers(int[] height) { |
| 39 | int left = 0, right = height.length - 1; |
| 40 | int maxArea = 0; |
| 41 | |
| 42 | // Move pointers toward each other |
| 43 | while (left <= right) { |
| 44 | int width = right - left; // Distance between lines |
| 45 | int minHeight = Math.min(height[left], height[right]); |
| 46 | int area = minHeight * width; // Compute water contained |
| 47 | |
| 48 | maxArea = Math.max(maxArea, area); // Update max water |
| 49 | |
| 50 | // Move the pointer pointing to the shorter height |
| 51 | if (height[left] < height[right]) { |
| 52 | left++; // Move left pointer forward |
| 53 | } else { |
| 54 | right--; // Move right pointer backward |
| 55 | } |
| 56 | } |
| 57 | return maxArea; |
| 58 | } |
| 59 | } |
nothing calls this directly
no outgoing calls
no test coverage detected