26. Remove Duplicates from Sorted Array
题目:移除排序数组重复元素,使前n个数不重复
思路:设置一个指针k,标记目前不重复的最后一位,从前往后遍历,如果严格递增,就将该值覆盖k后一位,否则不进行操作,非常简单。好像是滴滴面到的题。
public class Solution {
public int removeDuplicates(int[] nums) {
int k = 0;
for(int i = 1; i < nums.length; i++){
if(nums[i] > nums[k]){
nums[++k] = nums[i];
}
}
return k+1;
}
}
题目:移除数组中所有与给定值相同的数。
思路:与26题方法完全一致。
public class Solution {
public int removeElement(int[] nums, int val) {
int k = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != val){
nums[k++] = nums[i];
}
}
return k;
}
}
题目:将数组中所有零元素移到最后。
思路:与27题完全一致,只是将最后的数全部置为零。
public class Solution {
public void moveZeroes(int[] nums) {
int k = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
nums[k++] = nums[i];
}
}
for(int i = k; i < nums.length; i++){
nums[i] = 0;
}
}
}
80. Remove Duplicates from Sorted Array II
题目:允许每个元素重复一次
思路:方法一样,从后往前进行比较
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length < 3) return nums.length;
int k = nums.length-2;
for(int i = nums.length-3; i >= 0; i--){
if(nums[i] != nums[k+1]){
int temp = nums[i];
nums[i] = nums[k-1];
nums[k-1] = temp;
k--;
}
}
for(int i = k; i < nums.length; i++){
nums[i-k] = nums[i];
}
return nums.length-k;
}
}
其实不用从后往前,从前往后也是一样的,这样少一次遍历。
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i - 2])
nums[i++] = n;
return i;
}
83. Remove Duplicates from Sorted List
题目:移除链表中重复的元素
思路:非递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p = head;
while(p.next != null){
if(p.next.val == p.val){
p.next = p.next.next;
}
else{
p = p.next;
}
}
return head;
}
}
递归
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
82. Remove Duplicates from Sorted List II
题目:移除链表中所有出现重复的元素。
思路:当第一个节点可能被滤掉的时候使用头结点更方便。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p = new ListNode(0);
p.next = head;
ListNode q = p;
while(p.next.next != null){
if(p.next.val == p.next.next.val){
int x = p.next.val;
while(p.next.next != null && p.next.next.val == x) p.next = p.next.next;
p.next = p.next.next;
}
else{
p = p.next;
}
if(p == null || p.next == null) break;
}
return q.next;
}
}
递归
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
if (head.next != null && head.val == head.next.val) {
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
return deleteDuplicates(head.next);
} else {
head.next = deleteDuplicates(head.next);
}
return head;
}