Two Sum
来源:互联网 发布:增值税发票的税率算法 编辑:程序博客网 时间:2024/06/14 03:27
Question: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.
问题:给一个整数数组,使数组中的两个数相加等于特定的一个数,返回两个数的索引。
假设每次输入将有一个特定的答案,不能重复使用数组中的元素
解题思路:遍历数组找到最大值和最小值,
分析数据:若每次输入有一个特定答案,则数组中最多两个数字相同;数组元素可能为负数
遍历数组,将元素存入相应数组对应索引中,并将其值给为当前数组元素索引值加1
若当前元素为正数则存入posx元素对应索引中,若其索引中以有值,则存入posy对应索引中,
若当前元素为负数则存入posz元素对应索引中
遍历原数组,用给定的特定值减当前元素,若所得值大于数组最大值小于数组最小值
若所得值大于0并且不等于当前元素,查看posx中所得值对应索引是否大于0,若大于0比较其值与当前元素索引号加1,存入result
若所得值大于0并且等于当前元素,查看posy中所得值对应索引是否大于0,若大于0比较其值与当前元素索引号加1,存入result
否则查看posz中所得值对应索引是否大于0,若大于0比较其值与当前元素索引号加1,存入result
返回result
int* twoSum(int* nums, int numsSize, int target) { int* result=malloc(sizeof(int)*2); int min=0; int max=nums[0]; for(int i=0;i<numsSize;i++){ if(nums[i]>max) max=nums[i]; if(nums[i]<min) min=nums[i]; } if(max<0) max=-max; int posx[max+1]; int posy[max+1]; int posz[-min+1]; memset(posx,0,sizeof(int)*(max+1)); memset(posy,0,sizeof(int)*(max+1)); memset(posz,0,sizeof(int)*(-min+1)); for(int i=0;i<numsSize;i++){ if(nums[i]>=0){ (posx[nums[i]]==0)?(posx[nums[i]]=i+1):(posy[nums[i]]=i+1); } else{ posz[-nums[i]]=i+1; } } int tar; for(int i=0;i<numsSize;i++){ tar=target-nums[i]; if(tar>=min&&tar<=max){ if(tar>=0) { if(tar!=nums[i]){ if(posx[tar]>0){ result[0]=(i+1<posx[tar])?i:(posx[tar]-1); result[1]=(i+1>posx[tar])?i:(posx[tar]-1); break; } } else if(posy[tar]>0){ result[0]=(i+1<posy[tar])?i:(posy[tar]-1); result[1]=(i+1>posy[tar])?i:(posy[tar]-1); break; } } else if(posz[-tar]>0){ result[0]=(i+1<posz[-tar])?i:(posz[-tar]-1); result[1]=(i+1>posz[-tar])?i:(posz[-tar]-1); break; } } } return result;}int * result=malloc(sizeof(int)*2)
定义int类型指针result申请2*sizeof(int)(即2*4)个字节
malloc在C语言中是一个申请内存单元的函数
void *memset(void *s, int ch, size_t n)
s为指针或数组 ch为赋给s的值 n为s的长度
memset:作用是在一段内存块中填充一个给定的值,对较大的结构体或数组进行清零操作速度很快
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- 笔记day2多进程
- 修改UITextfield的Placeholder字体的颜色
- hdu 3336 Count the string【kmp】
- 蒟蒻复习之—–对拍
- oracle定时任务
- Two Sum
- SDUT 2136 数据结构实验之二叉树的建立与遍历
- 三角形的判定
- TQ210裸机编程——uart
- install record
- 七大查找算法
- 图片压缩按质量压缩
- MVP的简单使用
- nginx upstream模块配置