A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Miss_Allsunday 中级黑马   /  2017-6-13 21:11  /  1406 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Miss_Allsunday 于 2017-6-13 21:39 编辑

1. Two Sum
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].
1. 两数之和
给一个整数数列,需要返回两个数的下标使得这两个数加起来等于指定的目标。
你可以假设每个输入有且只有一个解,并且你不能使用同样的元素两次。
举例:
数组nums = [2, 7, 11, 15], 目标target = 9, 因为 nums[0] + nums[1] = 2 + 7 = 9, 所以应返回数组[0, 1]

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
   
}
这个网站的150道题目据说都是相当经典的算法题,很多题目都是世界顶尖大公司譬如谷歌,亚马逊,微软,苹果,雅虎,领英,等等的面试题。是谢佳芯同学推荐的,值得用来锻炼大家的思维,特地拿来与大家分享。可惜的是上面并不支持用Objective-C语言,所以我选择了C语言版本的,当然Swift语言也是支持的。想要在网站上提交并测试,大家需要先注册个账号并登陆。答案可以发在评论里大家互相交流,但是测试还是需要在网站上进行,因为所有的测试条件都在网上,我是不能一个一个打出来的。
这道题的网址为 “https://leetcode.com/problems/two-sum/#/description”。

评分

参与人数 1黑马币 +5 收起 理由
zhao543 + 5 赞一个!

查看全部评分

2 个回复

倒序浏览
这道题需要注意,在函数里需要用到malloc方法在堆区手动分配一个空间,否则用arr[2]这种新建的数组在函数执行结束后内存会被释放。
以下是我的答案:

int* twoSum(int* nums, int numsSize, int target) {
    int *result = (int *) malloc(sizeof(int) * 2); // 手动在堆空间分配两个int大小的空间,并强制转换成int指针赋值到result上。
   
    for (int i = 0; i < numsSize - 1; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if ((nums[i] + nums[j]) == target) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
   
    // 没搜索到的时候赋值成-1也只是以防万一。
    result[0] = -1;
    result[1] = -1;
    return result;
}
回复 使用道具 举报
大神就是大神,此贴应该申请加精.
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马