Remove Element 解答

Question

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Solution -- Two Pointers

Remember that p1 starts from -1.

 1 public class Solution {
 2     public int removeElement(int[] nums, int val) {
 3         int length = nums.length;
 4         if (length == 0)
 5             return 0;
 6         if (length == 1) {
 7             if (nums[0] == val)
 8                 return 0;
 9             else
10                 return 1;
11         }
12         int p1 = -1, p2 = 0;
13         while (p2 < length) {
14             if (nums[p2] != val) {
15                 p1++;
16                 nums[p1] = nums[p2];
17                 p2++;
18             } else {
19                 p2++;
20             }
21         }
22         return p1 + 1;
23     }
24 }
posted @ 2015-09-11 05:51  树獭君  阅读(126)  评论(0编辑  收藏  举报