2.1.1 Remove Duplicates from Sorted Array
来源:互联网 发布:软件研发费用 编辑:程序博客网 时间:2024/06/05 20:53
问题
答案
#include <stdio.h>#include <stdlib.h>//打印数组void print_array(int *pArry, int len){ int i; for (i = 0; i < len; i++) { printf("%08x, ", *(pArry+i)); if (!((i+1)%4)) printf("\n"); } printf("\n");}//生成已排序的数组void get_sorted_array(int *pArry, int len){ int i, j, k; i = 1; j = 0; while (j < len) { for (k = 0; k < i; k++) pArry[k+j] = i; j += i; i++; }}//移除数组中重复元素int remove_duplicates(int *pArry, int len){ int old_idx; //save last valid data in array, also new length of array int new_idx; //save next non-duplicate data in array old_idx = 0; new_idx = 1; while (new_idx < len) { while (pArry[old_idx] == pArry[new_idx]) { new_idx++; } if (old_idx != new_idx-1) { old_idx++; pArry[old_idx] = pArry[new_idx]; } new_idx++; } return old_idx;}int main(void){ int *pArray; int len; printf("please input len:"); scanf("%d", &len); pArray = (int *)malloc(len * sizeof(int)); get_sorted_array(pArray, len); printf("before sorted:\n"); print_array(pArray, len); len = remove_duplicates(pArray, len); printf("\n"); printf("after sorted:\n"); print_array(pArray, len); return 0;}
结果
分析
看了其它代码的实现,发现自己的代码不够简洁,所以做了些修改。
//其他人的代码//优点:代码简洁,需注意先自增再赋值//缺点:赋值次数较多int remove_duplicates_2(int *pArry, int len){ int i, idx; idx = 0; for (i = 1; i < len; i++) { if (pArry[idx] != pArry[i]) pArry[++idx] = pArry[i]; } return idx+1;}//自己优化后的代码//优点:代码简洁,需注意循环里每次只执行一个分支,用外层for循环代替了原来内层的while循环//缺点:无int remove_duplicates_3(int *pArry, int len){ int old_idx; int new_idx; for (old_idx = 0, new_idx = 1; new_idx < len; new_idx++) { if (pArry[old_idx] == pArry[new_idx]) { new_idx++; } else if (old_idx != new_idx-1) { pArry[++old_idx] = pArry[new_idx]; } } return old_idx+1;}
0 0
- 2.1.1 Remove Duplicates from Sorted Array
- 2.1.1 Remove Duplicates from Sorted Array
- 1: Remove Duplicates from Sorted Array
- LeetCode 2.1.1 Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates From Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- LAMP LAMP环境搭建【rpm】+ 实例应用
- C#的Task多线程编程
- 文件和参数一起上传到服务器
- MYSQL使用手册
- 静态库与动态库介绍(.a库资源处理需验证补充)
- 2.1.1 Remove Duplicates from Sorted Array
- android - open failed: EROFS (Read-only file system)
- iOS封装静态库,也就是.a文件
- zip,jar,tar.gz无需解压读取文件内容
- 工作总结20151209
- xml规范
- Lucene学习(三):综述Lucene的索引文件格式
- 导航栏(Header)和(Footer)的使用简介
- hadoop实战应用