LeetCode1.Two Sum

1.题目


2.题意

返回相加的两数等于特定值的索引

3.我的解法   

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int *a = (int*)malloc(2*sizeof(int));
    for(int i = 0;i<numsSize;i++)
    {
        for(int j = i+1;(j<numsSize && j != i);j++)
        {
            if(nums[i] + nums[j] == target)
            {
                a[0] = i;
                a[1] = j;
            }
        }
    }
    return a;
}

这是比较垃圾的方法,只5.21%。

4.优秀方法

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
typedef struct Node{  /*先定义一个结点,有键值,还有一个指向next 的指针*/
	int key;
	int value;
	struct Node* next;
}Node;

typedef struct HashSet{  /*定义hashset,首先是大小,然后设置一个指向node地址(node*)的指针table,即指向指针的指针*/
	int mapSize;
	Node** table;
}HashSet;

void initMap(HashSet* set, int mapSize){
/*初始化map,先设置大小,再给table分配内存,分配语句是这样一个构造,(要分配的变量类型,这里就是node**)+
malloc+(sizeof(基础类型node*)*基础类型的大小数量);再用memset,这个函数是将set->table以后的sizeof(Node*) * mapSize
个字节的内容全部替换为0*/
    set->mapSize=mapSize;
	set->table = (Node**)malloc(sizeof(Node*) * mapSize);
	memset(set->table,0,sizeof(Node*) * mapSize);
}

bool addData(HashSet* set,int key,int value){
	/*这里的key取了具体值,value是索引下标;这里的hash对负数取反,然后用求余做hash值,定义一个node类型指针ptr,指向代表hash值的table位置
	这个while的作用是判断有没有加入重复的数据,当一个新值进来了,ptr必定指向null,也就是跳过while,执行下面的key,value赋值,同时插入table[hash]对应的后面
	当一个旧值,重复值进来了,ptr一定指向一个不为空的地址,执行while,相当于处理冲突*/ 
	int hash = key > 0 ? key : -key;
	hash%=set->mapSize;
	Node *ptr = set->table[hash];

	while(ptr!=NULL){
		if(ptr->key==key){
			return false;
		}
		ptr=ptr->next;
	}
	ptr=malloc(sizeof(Node));
	ptr->key=key;
	ptr->value=value;
	ptr->next=set->table[hash];
	set->table[hash]=ptr;

	return true;
}

bool containsKey(HashSet* set, int key){
	/*这个函数主要是判断hashtab里面是否含有重复值,用到的是上面的while*/ 
	int hash = key>0 ? key:-key;
	hash%=set->mapSize;
	Node* ptr=set->table[hash];

	while(ptr!=NULL){
		if(ptr->key==key){
			return true;
		}
		ptr=ptr->next;
	}
	return false;
}

int getValue(HashSet* set,int key){
	/*与上面的函数功能类似,只不过返回的是value值或者0*/
	int hash = key>0 ? key:-key;
	hash%=set->mapSize;
	Node* ptr=set->table[hash];

	while(ptr!=NULL){
		if(ptr->key==key){
			return ptr->value;
		}
		ptr=ptr->next;
	}

	return 0;

}

int* twoSum(int* nums, int numsSize, int target) {
    HashSet map; 
    initMap(&map,numsSize);
    int* ret = (int*)malloc(sizeof(int)*2);
    for(int i=0;i<numsSize;i++){
        if(containsKey(&map,target-nums[i])){
            ret[0]=getValue(&map,target-nums[i]);
            ret[1]=i;
            return ret;
        }
        else{
            addData(&map,nums[i],i);
        }
    }
    return -1;
}
优于98%,使用hashtable

猜你喜欢

转载自blog.csdn.net/baidu_31257925/article/details/80248807
今日推荐