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

本是古典 何须时尚 2022-10-08 11:21 274阅读 0赞

题目要求:

给定一个整数数组 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]

[程序代码]

  1. #include<stdio.h>
  2. #define MAXSIZE 5
  3. #define OK 1
  4. #define NotFound -1
  5. #define ERROR -2
  6. typedef short Status;
  7. Status Resolution(short *nums, short Size, short target, short *x, short *y);
  8. Status InitArray(short *nums, short Size);
  9. Status Traverse(short *nums, short Size);
  10. short ElemCount(short *nums, short Size);
  11. Status GetInput(short *nums, short Size);
  12. Status Traverse(short *nums, short Size);
  13. int main()
  14. {
  15. short nums[MAXSIZE];/* 整数数组 */
  16. short target;/* 整数目标值 */
  17. short x = -1, y = -1;/* 记录匹配元素的坐标 */
  18. GetInput(nums, MAXSIZE);
  19. Traverse(nums, ElemCount(nums, MAXSIZE));
  20. fscanf(stdin, ", target = %hd", &target);
  21. if(Resolution(nums, ElemCount(nums, MAXSIZE), target, &x, &y) == OK)
  22. {
  23. /* 匹配成功 */
  24. fprintf(stdout, "[%hd,%hd]\n", x, y);
  25. }
  26. else
  27. {
  28. fprintf(stdout, "匹配失败.\n");
  29. }
  30. return 0;
  31. }
  32. /* */
  33. Status Traverse(short *nums, short Size)/* Size为数组元素个数 */
  34. {
  35. short i;
  36. for(i = 0; i < Size; i ++)
  37. {
  38. fprintf(stdout, "%hd ", *(nums + i));
  39. }
  40. fputc('\n', stdout);
  41. return OK;
  42. }
  43. /* */
  44. Status GetInput(short *nums, short Size)/* Size为缓冲区最大容量 */
  45. {
  46. short i = 0;
  47. while(getchar() != '[')
  48. {
  49. ;
  50. }/* 将"nums = ["全部读走 */
  51. fscanf(stdin, "%hd", nums + i);
  52. i ++;
  53. while(getchar() != ']')
  54. {
  55. fscanf(stdin, "%hd", nums + i);
  56. i ++;
  57. if(i == Size)
  58. {
  59. while(getchar() != ']')
  60. {
  61. ;
  62. }/* 清空输入缓冲区至']' */
  63. break;
  64. }
  65. }
  66. while(i < Size)
  67. {
  68. *(nums + i) = -1;
  69. i ++;
  70. }/* 将未用的空间全部置为-1 */
  71. return OK;
  72. }
  73. /* 统计数组中有效元素的个数 */
  74. short ElemCount(short *nums, short Size)
  75. {
  76. short size_infact = 0;/* 实际上数组元素的个数 */
  77. short i;
  78. for(i = 0; i < Size && nums[i] != -1; i ++)
  79. {
  80. size_infact ++;
  81. }
  82. return size_infact;
  83. }
  84. /* 在该数组中找出和为目标值 target 的那两个整数, 并返回它们的数组下标 */
  85. Status Resolution(short *nums, short Size, short target, short *x, short *y)/* 注: Size为数组中有效元素的个数 */
  86. {
  87. short i, j;
  88. for(i = 0; i < Size - 1; i ++)
  89. {
  90. for(j = i + 1; j < Size; j ++)
  91. {
  92. if(*(nums + i) + *(nums + j) == target)
  93. {
  94. *x = i;
  95. *y = j;
  96. return OK;
  97. }
  98. }
  99. }
  100. *x = *y = -1;
  101. return NotFound;
  102. }

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读