다른 배열에 따라 정렬
'다른 배열에 따라 정렬' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'다른 배열에 따른 정렬' 문제는 배열 섹션의 주요 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
다른 배열에 따른 정렬의 논리 흐름을 시각화합니다.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
다른 배열에 따라 정렬에 대한 문제 설명을 주의 깊게 읽어보세요.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
arr2에 정의된 순서에 따라 arr1의 요소를 정렬하는 함수 sort_by_order(arr1, arr2)을 작성하세요. arr2에 나타나는 arr1의 요소는 arr2에 나타나는 순서대로 먼저 와야 합니다. arr2에 없는 요소는 정렬된(오름차순) 순서로 끝에 표시되어야 합니다.
- •1 <= len(arr1) <= 10^5
- •0 <= len(arr2) <= 100
- •Elements of arr2 are distinct
예
arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8], arr2 = [2, 1, 8, 3]
[2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]
First all 2s, then 1s, then 8s, then 3s (order from arr2). Remaining [5,6,7,9] sorted ascending.
arr1 = [4, 5, 6], arr2 = [6, 4]
[6, 4, 5]
6 first, then 4 (per arr2 order). 5 is not in arr2, goes at end.
arr1 = [1, 2, 3], arr2 = []
[1, 2, 3]
No order specified, so sort ascending.
Need a Hint?
Edge Cases to Watch
- 빈 입력 구조
- 단일 요소 입력
- 큰 수치 범위
해결할 준비가 되셨나요?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
인터뷰 통찰력 및 변형
복잡성 분석 분석
왜 시간인가?: Directly evaluates all possibilities.
왜 우주인가?: Uses standard local memory.
왜 시간인가?: Optimized paths reduce total operations.
왜 우주인가?: May trade memory for speed.
최적화된 솔루션 Python 코드
최적화된 솔루션 Python 코드
from collections import Counter
def sort_by_order(arr1, arr2):
# Optimized: Use hash map for frequency counting
counts = Counter(arr1)
res = []
# Process elements in order of arr2
for x in arr2:
if x in counts:
res.extend([x] * counts[x])
del counts[x]
# Process remaining elements sorted
remaining = sorted(counts.elements())
return res + remaining무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
def sort_by_order(arr1, arr2):
# Brute force: Build result by searching arr2 elements in arr1
res = []
visited = [False] * len(arr1)
for x in arr2:
for i in range(len(arr1)):
if arr1[i] == x:
res.append(arr1[i])
visited[i] = True
# Add remaining elements in sorted order
remaining = sorted([arr1[i] for i in range(len(arr1)) if not visited[i]])
return res + remainingAlgorithm Pattern Checklist
When dealing with Arrays data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
표준 배열 문제 속성이 적용됩니다.
관련 질문
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
권장 Python 리소스
관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.
Python 생성기
Python 생성기와 Yield 문을 사용하여 최소한의 메모리 공간으로 대규모 데이터세트를 처리하는 방법을 알아보세요. 마스터 생성기 표현식.
Python에서 목록을 정렬하는 방법(오름차순 및 내림차순)
sort() 메서드와 sorted() 함수를 사용하여 Python에서 목록을 정렬하는 방법을 알아보세요. 사용자 정의 키 정렬 및 역순 예시를 살펴보세요.
Python 연산자 치트 시트
Python의 산술, 비교, 논리, 비트, 할당 및 항등 연산자를 마스터하세요.
Python 데코레이터와 데코레이터 디자인 패턴: 주요 차이점
Python 데코레이터와 클래식 데코레이터 디자인 패턴을 비교해 보세요. 실행 가능한 코드를 사용하여 정의 시 함수 래핑과 런타임 동적 개체 구성 간의 차이점을 이해합니다.