Easy-30
来源:互联网 发布:linux git clone 路径 编辑:程序博客网 时间:2024/06/06 00:35
leetcode 349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return[2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
AC:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
int* result=(int*)malloc((nums1Size>nums2Size?nums1Size:nums2Size)*sizeof(int));
int length=0;
for(int i=0;i<nums1Size;i++){
for(int j=0;j<nums2Size;j++){
if(nums1[i]==nums2[j]){
result[length]=nums1[i];
length++;
}
}
}
for(int i=0;i<length-1;i++){
for(int j=i+1;j<length;j++){
if(result[i]==result[j]){
int k=result[j];
result[j]=result[length-1];
result[length-1]=k;
length--;
j--;
}
}
}
*returnSize=length;
int* result1=(int*)malloc(length*sizeof(int));
for(int i=0;i<length;i++)
{
result1[i]=result[i];
}
free(result);
return result1;
}
int length=0;
for(int i=0;i<nums1Size;i++){
for(int j=0;j<nums2Size;j++){
if(nums1[i]==nums2[j]){
result[length]=nums1[i];
length++;
}
}
}
for(int i=0;i<length-1;i++){
for(int j=i+1;j<length;j++){
if(result[i]==result[j]){
int k=result[j];
result[j]=result[length-1];
result[length-1]=k;
length--;
j--;
}
}
}
*returnSize=length;
int* result1=(int*)malloc(length*sizeof(int));
for(int i=0;i<length;i++)
{
result1[i]=result[i];
}
free(result);
return result1;
}
tips: 特别简单的方法,时间复杂度很高。要注意的是在去重的时候,我选择把重复的放到末尾,然后长度减一,此时需要j--,这样避免从末尾换到第j个位置的元素没有进行查重处理。
0 0
- Easy-30
- easy
- Easy
- Easy-题目30:66. Plus One
- Creating a WebDynpro ALV Application in 30 easy steps
- Creating a WebDynpro ALV Application in 30 easy steps
- Easy Plugs
- easy problem
- So Easy!
- so easy
- easy explorer
- Easy Explore
- Easy Task
- Easy Task
- Easy CHM
- HDU2699+Easy
- HDU4648+Easy
- Easy billiards
- Mysql 远程连接失败的问题
- 40. Combination Sum II
- AtCoder:Median Pyramid Easy(思维)
- 二叉树的学习(中)
- 【动态规划】Leetcode编程题解:198. House Robber Add to List
- Easy-30
- 该网页无法正常运作 HTTP ERROR 500
- Android源码:xml文件是如何加载到屏幕上的(二)
- IP协议详解
- 解决NS3中打开XML文件提示NetAnim版本必须大于等于3.108的问题
- web项目添加logback日志
- C++之二叉查找树
- Git 和 SVN 之间的五个基本区别
- 【Redis笔记-1】Redis Desktop Manager On Mac