题目:Remove Duplicates from Sorted Array
删除数组中重复元素。
public class Solution { public int removeDuplicates(int[] nums) { int i = 0,j = 1; while(j < nums.length){ if(nums[j] != nums[j - 1]){ nums[i++] = nums[j - 1]; if(j == nums.length - 1)nums[i++] = nums[j]; }else if(j == nums.length - 1){ nums[i++] = nums[j]; } j++; } if(nums.length == 1)return 1; return i; } }
题目:Remove Duplicates from Sorted ArrayII
保证数组中同一元素重复次数不超过2次。
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 1)return 1; int count = 0,i = 0,j = 1; while(j < nums.length){ if(nums[j - 1] == nums[j]){ count++; }else{ if(count >= 1){ nums[i++] = nums[j - 2]; count = 0; } nums[i++] = nums[j - 1]; } if(j == nums.length - 1){ if(nums[j - 1] == nums[j])nums[i++] = nums[j - 1]; nums[i++] = nums[j]; } j++; } return i; } }
题目:Remove Duplicates from Sorted List II
删除已序链表中的重复元素。
package com.example.medium; /** * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. * For example, * Given 1->2->3->3->4->4->5, return 1->2->5. * Given 1->1->1->2->3, return 2->3. * @author FuPing * */ public class DeleteDuplicates { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null)return head;//头为空 ListNode p = head.next,pre = head; boolean flag = false,headFlag = false; if(pre.val == p.val)headFlag = true;//头元素是否重复 while(p.next != null){ if(p.val == p.next.val){ p.next = p.next.next; flag = true; }else{ if(flag){//有重复元素 pre.next = p.next; flag = false; }else{ pre = pre.next; } p = p.next; } } if(flag)pre.next = p.next; if(headFlag){//删除头部 if(head.next != null && head.val == head.next.val) return head.next.next; return head.next; } return head; } public static void main(String[] args) { // TODO Auto-generated method stub } }