码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Element 解答

时间:2015-09-11 06:44:07      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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 }

Remove Element 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4799838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!