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

Leetcode-Remove Element

时间:2014-11-29 10:12:55      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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:

 1 public class Solution {
 2     public int removeElement(int[] A, int elem) {
 3         int head = 0;
 4         int end = A.length-1;
 5 
 6         while (head<end){
 7             while (head<A.length && A[head]!=elem) head++;
 8             if (head>=end) break;
 9             while (end>=0 && A[end]==elem) end--;
10             if (head>=end) break;
11             int temp = A[head];
12             A[head] = A[end];
13             A[end] = temp;
14         }
15         
16         int len = A.length;
17         for (int i=0;i<A.length;i++)
18             if (A[i]==elem){
19                 len = i;
20                 break;
21             }
22 
23         return len;
24     }
25 }

 

Leetcode-Remove Element

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4130155.html

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