博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1. Two Sum (Easy)
阅读量:7045 次
发布时间:2019-06-28

本文共 947 字,大约阅读时间需要 3 分钟。

Description

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.

Translation

整形数组中每个元素均不相同,且两两相加的结果也不相同。给定某一目标数字,返回数组中相加结果为给定目标数字的两个元素的下标。

Example

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

Solution

/** * Note: The returned array must be malloced, assume caller calls free(). */

Method1 (循环遍历)

对数组内的元素两两逐次相加,记录其下标。

int* twoSum(int* nums, int numsSize, int target) {    int* arrIndices = (int*)malloc(sizeof(int) * 2);    for(i = 0; i < numsSize - 1; i++){        for(j = i + 1; j < numsSize; j++){            if (nums[i] + nums[j] == target){                flag[0] = i;                flag[1] = j;                break;            }            else                continue;        }    }    return arrIndices;}

时间复杂度: O(n2)

空间复杂度: O(1)

转载地址:http://bxhal.baihongyu.com/

你可能感兴趣的文章
Linux 安装 SonarQube 6.0 及Maven项目的使用
查看>>
LibreOffice 6.2.2 发布,功能强大的开源办公套件
查看>>
「架构技术专题」什么是架构设计的五个核心要素?(3)
查看>>
数据分析展现工具SDC UE
查看>>
windows下cmd时复制dos中的内容 错误信息等
查看>>
DNA sequence(映射+BFS)
查看>>
js_exception_01_ajax_能正常执行后台方法,可是无法返回
查看>>
一个数据库迁移案例解析
查看>>
网站安全-浅谈用户密码暴力破解
查看>>
论人性中的野性
查看>>
PyTorch 实战-用 Numpy 热身
查看>>
TensorFlow 多 GPU 处理并行数据
查看>>
整理一些计算机基础知识!
查看>>
史上最快! 10小时大数据入门(二)-初识Hadoop
查看>>
HyperLedger Fabric 1.2 官方End-2-End运行(8)
查看>>
告知服务器意图的 HTTP 方法
查看>>
Java编程思想-Chapter15-泛型
查看>>
js浮点数存储精度丢失原理
查看>>
友达光电(昆山)第六代LTPS液晶面板厂 成功点亮首片5.5吋Full HD面板 缔造最快速量产记录 展现领先LTPS技术实力...
查看>>
Chrome 暗黑模式最新进展:现在可自动跟随系统主题设置
查看>>