给定一个整数数组 nums 和一个整数目标值 target, 请你在该数组中找出和为目标值 target 的那两个整数, 并返回它们的数组下标

  • Post author:
  • Post category:其他

题目要求:

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。

[注]从前往后进行匹配, 一旦匹配成功, 便结束程序.

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

[程序代码] 

#include<stdio.h>
#define MAXSIZE 5
#define OK 1
#define NotFound -1
#define ERROR -2
typedef short Status;
Status Resolution(short *nums, short Size, short target, short *x, short *y);
Status InitArray(short *nums, short Size);
Status Traverse(short *nums, short Size);
short ElemCount(short *nums, short Size);
Status GetInput(short *nums, short Size);
Status Traverse(short *nums, short Size);
int main()
{
    short nums[MAXSIZE];/* 整数数组 */
    short target;/* 整数目标值 */
    short x = -1, y = -1;/* 记录匹配元素的坐标 */
    GetInput(nums, MAXSIZE);
    Traverse(nums, ElemCount(nums, MAXSIZE));
    fscanf(stdin, ", target = %hd", &target);
    if(Resolution(nums, ElemCount(nums, MAXSIZE), target, &x, &y) == OK)
    {
        /* 匹配成功 */
        fprintf(stdout, "[%hd,%hd]\n", x, y);
    }
    else
    {
        fprintf(stdout, "匹配失败.\n");
    }
    return 0;
}
/* */
Status Traverse(short *nums, short Size)/* Size为数组元素个数 */
{
    short i;
    for(i = 0; i < Size; i ++)
    {
        fprintf(stdout, "%hd ", *(nums + i));
    }
    fputc('\n', stdout);
    return OK;
}
/* */
Status GetInput(short *nums, short Size)/* Size为缓冲区最大容量 */
{
    short i = 0;
    while(getchar() != '[')
    {
        ;
    }/* 将"nums = ["全部读走 */
    fscanf(stdin, "%hd", nums + i);
    i ++;
    while(getchar() != ']')
    {
        fscanf(stdin, "%hd", nums + i);
        i ++;
        if(i == Size)
        {
            while(getchar() != ']')
            {
                ;
            }/* 清空输入缓冲区至']' */
            break;
        }
    }
    while(i < Size)
    {
        *(nums + i) = -1;
        i ++;
    }/* 将未用的空间全部置为-1 */
    return OK;
}
/* 统计数组中有效元素的个数 */
short ElemCount(short *nums, short Size)
{
    short size_infact = 0;/* 实际上数组元素的个数 */
    short i;
    for(i = 0; i < Size && nums[i] != -1; i ++)
    {
        size_infact ++;
    }
    return size_infact;
}
/* 在该数组中找出和为目标值 target 的那两个整数, 并返回它们的数组下标 */
Status Resolution(short *nums, short Size, short target, short *x, short *y)/* 注: Size为数组中有效元素的个数 */
{
    short i, j;
    for(i = 0; i < Size - 1; i ++)
    {
        for(j = i + 1; j < Size; j ++)
        {
            if(*(nums + i) + *(nums + j) == target)
            {
                *x = i;
                *y = j;
                return OK;
            }
        }
    }
    *x = *y = -1;
    return NotFound;
}

 


版权声明:本文为weixin_42048463原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。