LeetCode - Two Sum
来源:互联网 发布:淘宝生死狙击卖号平台 编辑:程序博客网 时间:2024/05/20 04:49
Leet Code - Two Sum
记录代码
/* Problem: * Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution.And you may not use the same element twice. */#include<stdio.h>#include<string.h>#include<malloc.h>#define HASH_LEN 1000typedef struct Data{ int value; int index; struct Data *next;}Data;typedef struct Hash{ Data *head; Data *end;}Hash;void insertData(Hash *hash,Data *data);int searchData(Hash *hash,int value,int i);int *twoSum(int *nums,int numsSize,int target);int main(void){ int numsSize,target; scanf("%d",&numsSize); int nums[numsSize]; printf("Please input the data:\n"); for(int i=0;i<numsSize;i++) scanf("%d",&nums[i]); printf("Please input the target:\n"); scanf("%d",&target); int *ans; ans=twoSum(nums,numsSize,target); if(ans) for(int i=0;i<2;i++) printf("%d ",*(ans+i)); else printf("No answers."); return 0;}void insertData(Hash *hash,Data *data){ int key=(unsigned int)(data->value)%HASH_LEN; if(!hash[key].head){ hash[key].head=data; hash[key].end=data; } else{ hash[key].end->next=data; hash[key].end=data; }}int searchData(Hash *hash,int value,int i){ int key=(unsigned int)value%HASH_LEN; Data *p=hash[key].head; while(p){ if(p->value==value&&p->index!=i) return p->index; p=p->next; } return 0;}int *twoSum(int *nums,int numsSize,int target){ int *ans=(int *)malloc(2*sizeof(int)); Hash hash[HASH_LEN]; memset(hash,0,sizeof(Hash)*HASH_LEN); Data data[HASH_LEN]; memset(data,0,sizeof(Data)*HASH_LEN); for(int i=0;i<numsSize;i++){ data[i].value=nums[i]; data[i].index=i; insertData(hash,&data[i]); } for(int i=0;i<numsSize;i++){ int x=i; int y=searchData(hash,target-nums[i],i); if(y){ ans[0]=x<y?x:y; ans[1]=x+y-ans[0]; break; } else return NULL; } return ans;}
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- Redis 3.0集群搭建测试(二)
- 237. Delete Node in a Linked List
- Redis 订阅与发布
- 如果交叉编译工具出现 没有那个文件或目录
- Redis Java客户端Jredis
- LeetCode - Two Sum
- 文档格式之间的转换使用
- web开发中404错误总结
- Big-man酷谈overflow
- java WEB常见的错误代码
- Java之Number类
- 不要做一个浮躁的程序员
- Java之String类
- 2.5 VB编程基础--运算符和表达式