java 第二周

删除排序数组中的重复项

给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

来源:力扣(LeetCode)

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        int n = 0;
        for (int i = 1 ; i < nums.length ; i++){
            if (nums[n] != nums[i]){
                n++;
                nums[n] = nums[i];
            }
        }
        return n+1;
    }
}
 
 

// 对一个数组进行希尔排序。
public class One
{

public static void main(String[] args)
{
/*希尔排序的原理是先将要排序的数组元素分成多个子序列,
使得每个子序列的元素个数相对较少,
然后对各个子序列进行直接插入排序,
等到整个待排序列基本上有了顺序后,
最后在对所有的元素进行一次直接插入排序。*/
int i = 0;
int a[] = {2,3,4,63,67,8,42,45};
int len = a.length;
shellSort(a);
for (i = 0; i < len; i++) {
System.out.print(a[i] + " ");
}
}

private static void shellSort(int[] a)
{
int length = a.length;
int i, j;
int h;
int temp;
for (h = length / 2; h > 0; h = h / 2) {
for(i = h; i < length; i++) {
temp = a[i];
for(j = i - h; j >= 0; j -= h) {
if(temp < a[j]) {
a[j+h] = a[j];
}
else
break;
}
a[j+h] = temp;
}
}
}

 
 

猜你喜欢

转载自www.cnblogs.com/bukeke/p/12891666.html
今日推荐