> 백엔드 개발 > C++ > 본문

두 개의 정렬된 배열에서 흔하지 않은 요소를 인쇄합니다.

WBOY
풀어 주다: 2023-09-12 22:09:16
앞으로
1435명이 탐색했습니다.

두 개의 정렬된 배열에서 흔하지 않은 요소를 인쇄합니다.

두 개의 정렬된 배열이 있는 경우 출력에는 공통되지 않은 요소가 표시되어야 합니다.

Given : array1[]= {1, 4, 6, 9, 12}
   array2[]= {2, 4, 7, 8, 9, 10}
Output : 1 2 6 7 8 10 12
로그인 후 복사

알고리즘

START
Step 1 -> declare two arrays array1 and array2 with elements as int and variables n1, n2, i to 0 and j to 0
Step 2 -> calculate number of elements in array1 sizeof(array1)/sizeof(array1[0])
Step 3-> calculate number of elements in array2 sizeof(array2)/sizeof(array2[0])
Step 4 -> Loop While till i<n1 and j<n2
   IF array1[i]<array2[j]
      Print array1[i++]
   End IF
      ELSE If array1[i] > array2[j]
         Print array2[j++ ]
      End ELSE IF
   ELSE
      i++ and j++
   End ELSE
Step 5 -> End Loop While
Step 6 -> loop While i < n1 && array1[i]!=array2[j]
   Print array1[i++]
Step 7 -> End Loop While
Step 8 -> loop While j < n2 && array2[j]!=array1[i]
   Print array2[j++]
Step 9 -> End Loop While
STOP
로그인 후 복사

Example

의 중국어 번역은 다음과 같습니다.

Example

#include <stdio.h>
int main(int argc, char const *argv[]) {
   int array1[]= {1, 4, 6, 9, 12};
   int array2[]= {2, 4, 7, 8, 9, 10};
   int n1, n2, i=0, j=0;
   n1 = sizeof(array1)/sizeof(array1[0]); //Calculating number of elements in array1
   n2 = sizeof(array2)/sizeof(array2[0]); //Calculating number of elements in array2
   while(i < n1 && j < n2) {
      if(array1[i] <array2[j]) //checking whether the element of array1 is smaller than array2
         printf("%d</p><p>", array1[i++]);
      else if (array1[i] > array2[j]) //checking whether the element of array2 is smaller than array1
         printf("%d</p><p>", array2[j++]);
      else { //if they are equal increment both i and j      
         i++;
         j++;
      }
   }
   while(i < n1 && array1[i]!=array2[j]) //print remaining array1
      printf("%d</p><p>", array1[i++]);
   while(j < n2 && array2[j]!=array1[i]) //print remaining array1
      printf("%d</p><p>", array2[j++]);
   return 0;
}
로그인 후 복사

Output

위 프로그램을 실행하면 다음 출력을 생성합니다

1
2
6
7
8
10
12
로그인 후 복사

위 내용은 두 개의 정렬된 배열에서 흔하지 않은 요소를 인쇄합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!