투섬 II
'Two Sum II' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'Two Sum II' 문제는 Two Pointers 섹션의 핵심 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
Two Sum II의 논리 흐름 시각화.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Two Sum II의 문제 설명을 주의 깊게 읽어보세요.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
이미 감소하지 않는 순서로 정렬된 1부터 인덱스가 지정된 정수 배열 numbers이 주어지면 특정 target 숫자에 더해지는 두 개의 숫자를 찾습니다.
두 숫자 index1 및 index2의 인덱스를 길이 2의 정수 배열 [index1, index2]로 1씩 더한 값으로 반환합니다.
동일한 요소를 두 번 사용할 수 없습니다. 솔루션은 일정한 추가 공간만 사용해야 합니다.
twoSum(numbers: List[int], target: int) -> List[int] 함수를 작성하세요.
- •2 <= len(numbers) <= 3 * 10^4
- •-1000 <= numbers[i] <= 1000
- •numbers is sorted in non-decreasing order
- •-1000 <= target <= 1000
- •Exactly one solution exists
예
numbers = [2, 7, 11, 15], target = 9
[1, 2]
2 + 7 = 9. The indices are 1 and 2 (1-indexed).
numbers = [2, 3, 4], target = 6
[1, 3]
2 + 4 = 6. The indices are 1 and 3 (1-indexed).
numbers = [-1, 0], target = -1
[1, 2]
-1 + 0 = -1. The indices are 1 and 2 (1-indexed).
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 코드
def two_sum_ii_opt(numbers, target):
l, r = 0, len(numbers) - 1
while l < r:
curSum = numbers[l] + numbers[r]
if curSum > target:
r -= 1
elif curSum < target:
l += 1
else:
return [l + 1, r + 1]
return []무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
def two_sum_ii_brute(numbers, target):
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
return [i + 1, j + 1]
return []Algorithm Pattern Checklist
When dealing with Two Pointers 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 루프를 사용하여 데이터를 반복하는 방법을 알아보세요. 대화형 예제를 통해 for 루프, while 루프, 중단, 계속 및 루프 모범 사례를 마스터하세요.
Python에서 두 목록을 병합하는 방법(연결 및 확장)
Python에서 두 목록을 병합하고 결합하는 가장 좋은 방법을 알아보세요. 플러스 연산자, 확장 메소드, 목록 풀기 및 체인 옵션을 비교하십시오.
Python 문자열 메서드 치트 시트
Python 문자열 조작에 대한 완전한 참조 가이드입니다. 문자열 속성의 서식 지정, 검색, 분할, 바꾸기 및 확인을 마스터합니다.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.