首页 > 其他 > 详细

Remove Element 解答

时间:2015-09-11 06:42:46      阅读:205      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!