remove-element

来源:互联网 发布:硬盘损坏数据恢复 编辑:程序博客网 时间:2024/06/15 18:27
packagecom.ytx.array;
/** 题目: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.
 *
 *@authoryuantian xin
 * 
 *  给定一个数组和一个值,删除该值的所有实例,并返回新的长度。元素的顺序可以被改变,也不关心最终的数组长度。
 * 
 *  双指针思想,一个快指针i,一个慢指针index
 */
publicclass Remove_element {
       
       public int removeElement(int[]A,int elem) {
             
             /*int len = A.length;
              if(len == 0) return 0;
             int index = 0;
              for(int i = 0; i <len; i++) {
                     if(A[i] !=elem) {
                            A[index++] = A[i];
                     }
              }
            return index; */
             int len = A.length;
             for(inti=0;i<len;){
                  if(elem==A[i]){
                      A[i]=A[--len];//若相同则把最后一个位置元素覆盖过来,且重新检查覆盖过来的元素
                   }else{
                       ++i;
                   }
               }
              return len;
        }
       
       publicstatic void main(String[]args) {
             
             int[]A={1,2,2,4,5,2,6,2,2,2,7};
             intelem = 2;
             intnewlength = newRemove_element().removeElement(A,elem);
             for(inti = 0; i < newlength;i++) {
                    System.out.print(A[i] + " ");
             }
       }
}
原创粉丝点击