橋声 2015-08-16 12:43 采纳率: 0%
浏览 1633
已结题

leetCode上Easy级别题目求解

题目:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
大概意思就是去掉一个有序数组重复的元素。
我按照网上的答案运行了下,发现结果不对啊?下面是代码,求解惑
public class Solution {
public static int removeDuplicate(int[] nums){

      if(nums.length == 0 || nums.length == 1) {
          return nums.length;
      }
      int index=0, i=1;
      while(i<nums.length) {
          if(nums[index] == nums[i]) {
              i++;
          }else {
              nums[++index] = nums[i];
              i++;

          }
      }
      return ++index;
}

public static void main(String[] args){
    int[] nums = new int[]{1, 1, 2};
    System.out.println("---------------");
    int length = removeDuplicate(nums);
    System.out.println(length);
    System.out.println(Arrays.toString(nums));
}

}
运行结果为:
---------------
2
[1, 2, 2]
但是按照题目的要求,数组A不是应该变成[1,2]了么?求大神分析下吧,C币实在不多,求帮忙。

  • 写回答

2条回答 默认 最新

  • threenewbee 2015-08-16 13:13
    关注

    如果返回的数组没有多余的元素,再返回长度就是多余。

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP