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

LeetCode(27)题解:Remove Element

时间:2015-06-19 01:26:31      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/remove-element/

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.

 

思路:

因为可以改变元素顺序,所以只需要把最后端的非val元素用最前端的val代替即可,前后两个指针同时移动直到相遇。

AC代码:

 

 

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val) {
 4         int i=0,n=nums.size()-1;
 5         if(n<0)
 6             return 0;
 7         while(nums[n]==val)
 8             n--;
 9         if(n<0)
10             return 0;
11         while(i<n){
12             while(nums[n]==val){
13                 n--;
14             }
15             if(i>n)
16                 break;
17             if(nums[i]==val){
18                 nums[i]=nums[n];
19                 n--;
20             }
21             i++;
22         }
23         while(nums[n]==val){
24                 n--;
25             }
26         return n+1;
27     }
28 };

 

LeetCode(27)题解:Remove Element

标签:

原文地址:http://www.cnblogs.com/aezero/p/4587375.html

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