算法面试——双指针:移动零、盛水容器、环形链表
·
双指针是在有序数组或链表上常用的优化技巧,把 O(n²) 的问题优化到 O(n)。
一、移动零
public void moveZeroes(int[] nums) {
int nonZero = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[nonZero];
nums[nonZero] = temp;
nonZero++;
}
}
}
二、盛最多水的容器
public int maxArea(int[] height) {
int max = 0, left = 0, right = height.length - 1;
while (left < right) {
int area = Math.min(height[left], height[right]) * (right - left);
max = Math.max(max, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max;
}
三、环形链表
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!
更多推荐
所有评论(0)