给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
第一题
来源:力扣(LeetCode)
链接:https: //leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处
看题解有三种写法,目前能力,只能暴力便利法
还有hash表的写法,以后再补充
/**
* Note: The returned array must be malloced, assume caller calls free().
返回的数组必须被分配空间
*/
int* twoSum(int* nums, int numsSize, int target,int *returnSize){
int *res= (int*)malloc(sizeof(int)*2);
*returnSize=0;
int i,j;
for(i=0;i<numsSize-1;i++)
for(j=i+1;j<numsSize;j++)
if(nums[i]+nums[j]==target)
{
res[0]=i;
res[1]=j;
*returnSize=2;
return res;
}
return res;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
第二题
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/*
思路:
1.先遍历两个链表 得到两个整数 2+4*10+3*100=342 ,5*1+6*10+4*100=465
2.两数相加 342+465=807
3.创建新的链表 存储整数807 807%10=7,80%10=0,8%10=8;
尾插法 7 0 8
*/
第一次代码如下leetcode执行代码测试用例输出正确没有报错 ,但提交出现错误
int traverseList(struct ListNode*l)
{
struct ListNode *p=l; //工作指针
int sum=0;
int mul=1; //倍数
while(p)
{
sum+=(p->val)*mul;
mul=mul*10;
p=p->next;
}
return sum;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
int sum1,sum2,sum;
sum1= traverseList(l1);
sum2= traverseList(l2);
sum=sum1+sum2;
printf("%d %d %d\n",sum1,sum2,sum);
struct ListNode *pre,*q,*cur;
pre=(struct ListNode*)malloc(sizeof(struct ListNode));
pre->val=0;
pre->next=NULL;//创建头节点
cur=pre;
while(sum)
{
int y=sum%10;
sum=sum/10;
q=(struct ListNode*)malloc(sizeof(struct ListNode));
q->val=y;
q->next=NULL;
cur->next=q;
cur=cur->next;
}
//q->next=NULL;
return pre->next;
}