1.哈希表法
#include<stdio.h>
#include<stdlib.h>
int func(int *arr,int len)
{int *hash=(int *)malloc(sizeof(int)*len);for(int i=0;i<len;i++){if(hash[arr[i]]==1){free(hash);return arr[i];}hash[arr[i]]=1;}free(hash);return -1;
}int main()
{int arr[5]={1,3,4,2,2};int len=sizeof(arr)/arr[0];int result=func(arr,len);printf("%d",result);
}
2.环形链表
#include<stdio.h>
#include<stdlib.h>
int func(int *arr,int len)
{int slow=arr[0];int fast=arr[0];do{slow=arr[slow];//arr[arr[0]]fast=arr[arr[fast]];//arr[arr[arr[0]]]} while (slow!=fast);slow=arr[0];while(slow!=fast){slow=arr[slow];fast=arr[fast];}return slow;
}int main()
{int arr[5]={1,3,4,2,2};int len=sizeof(arr)/arr[0];int result=func(arr,len);printf("%d ",result);
}
扩展重复的字符串
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* func(char *arr[],int len)
{for(int i=0;i<len;i++){for(int j=0;j<i;j++){if((strcmp(arr[i],arr[j]))==0){return arr[i];}}}
}int main()
{char *arr[]={"apple","bnana","grape","apple","orange"};int len=sizeof(arr)/sizeof(arr[0]);char* result=func(arr,len);printf("%s ",result);}
对象扩展
#include<iostream>
using namespace std;
class Student
{
public:string name;int age;Student (string name="",int age=0):name(name),age(age){}bool operator==(const Student &a ){return (a.name==this->name);}};int func(int *arr,int len)
{int *hash=(int *)malloc(sizeof(int)*len);for(int i=0;i<len;i++){if(hash[arr[i]]==1){free(hash);return arr[i];}hash[arr[i]]=1;}free(hash);return -1;
}int main()
{Student s1("apple1",1);Student s2("apple",1);s1==s2;if(s1==s2){cout<<"yes"<<endl;}else{cout<<"no"<<endl;}// int arr[5]={1,3,4,2,2};// int len=sizeof(arr)/arr[0];// int result=func(arr,len);// printf("%d ",result);}