leetcode 1. Two Sum (C语言)12
2017-09-25 19:35
477 查看
贴原题:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解析:
本题就是给出一组数,和一个目标值,让我们找出数组中的两个数,使得两数之和等于目标值,并返回两个数在那个数组中的下标。
那么我们用一个嵌套循环,扫描到满足条件的两个数并返回其下标即可。
贴代码:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解析:
本题就是给出一组数,和一个目标值,让我们找出数组中的两个数,使得两数之和等于目标值,并返回两个数在那个数组中的下标。
那么我们用一个嵌套循环,扫描到满足条件的两个数并返回其下标即可。
贴代码:
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target) { int* reNums=(int *)malloc(2*sizeof(int)); for(int i=0; i<numsSize; i++) { int flag=0; for(int j=i+1; j<numsSize; j++) { if(*(nums+i)+*(nums+j)==target) { *reNums=i; *(reNums+1)=j; flag=1; break; } if(flag) { break; } } } return reNums; }
相关文章推荐
- [C语言][LeetCode][1]Two Sum
- 1---LeetCode【Two Sum】|C语言|总结
- LeetCode-Two Sum
- [leetcode]-507. Perfect Number(C语言)
- leetcode 12 Integer to Roman(整型数转换为罗马数字)
- [leetcode]-503. Next Greater Element II(C语言)
- leetcode-12 Integer to Roman
- LeetCode - Two Sum
- LeetCode1-Two Sum
- Leetcode116: Two Sum
- LeetCode刷题笔记 01 Two Sum
- [Leetcode] 1. Two Sum
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- LeetCode 1.Two Sum (Python)
- 【LeetCode编程学习(C语言)】1.Two Sum
- leetCode 12.Integer to Roman (整数转罗马数字) 解题思路和方法
- [leetcode]-231. Power of Two(C语言)
- C语言和设计模式(享元模式) 12
- Leetcode代码学习周记——Two Sum
- {LeetCode} 1. Two Sum