LeetCode编程练习 - Remove Duplicates from Sorted Array学习心得

题目:

      Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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
nums =[1,1,2],

      Your function should return length =2, with the first two elements ofnums being1 and2 respectively. It doesn't matter what you leave beyond the new length.

      就是说给定一个排序的数组,删除重复的位置,使得每个元素只出现一次,并返回新的长度。


思路:

    我的思路是一前一后循环索引数组nums中对的元素,当索引值不相等时将后面的索引值赋值给前面的索引值。

    但是运行程序会出现错误显示“不能将int[]类型转换为int型”,反复看了程序的逻辑认为没有什么问题后查看解决方案,发现跟解决方案还是有一定的偏差的。解决方案中是先定义一个变量i初始化为0,定义一个索引值j从数组的开始开始读取,以i为主体,判断所指数值是否相同,若不相同,i加1然后赋值返回有效长度,这样就把相同的值去掉了。


程序:

  错误代码:

LeetCode编程练习 - Remove Duplicates from Sorted Array学习心得


    更改后的代码:

LeetCode编程练习 - Remove Duplicates from Sorted Array学习心得