给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。C语言代码怎么写
时间: 2023-05-30 13:05:38 浏览: 64
```c
bool containsDuplicate(int* nums, int numsSize){
for(int i=0;i<numsSize;i++){
for(int j=i+1;j<numsSize;j++){
if(nums[i]==nums[j]){
return true;
}
}
}
return false;
}
```
或者使用哈希表的方式来优化时间复杂度:
```c
#include <stdbool.h>
#include <stdlib.h>
typedef struct hash_node{
int val;
struct hash_node *next;
}hash_node;
typedef struct hash_table{
int size;
hash_node **nodes;
}hash_table;
hash_table* create_hash_table(int size){
hash_table *table = (hash_table*)malloc(sizeof(hash_table));
table->size = size;
table->nodes = (hash_node**)calloc(size, sizeof(hash_node*));
return table;
}
void insert(hash_table *table, int val){
int key = abs(val) % table->size;
if(table->nodes[key] == NULL){
table->nodes[key] = (hash_node*)malloc(sizeof(hash_node));
table->nodes[key]->val = val;
table->nodes[key]->next = NULL;
}
else{
hash_node *pre = NULL;
hash_node *cur = table->nodes[key];
while(cur != NULL){
if(cur->val == val){
return;
}
pre = cur;
cur = cur->next;
}
pre->next = (hash_node*)malloc(sizeof(hash_node));
pre->next->val = val;
pre->next->next = NULL;
}
}
bool containsDuplicate(int* nums, int numsSize){
hash_table *table = create_hash_table(numsSize);
for(int i=0;i<numsSize;i++){
insert(table, nums[i]);
}
for(int i=0;i<table->size;i++){
if(table->nodes[i] != NULL){
if(table->nodes[i]->next != NULL){
return true;
}
}
}
return false;
}
```