ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 99클럽(2기) - 코테스터디 23일차 TIL # Array
    카테고리 없음 2024. 6. 22. 10:48

    LeetCode - 2089. Find Target Indices After Sorting Array

    You are given a 0-indexed integer array nums and a target element target.

    A target index is an index i such that nums[i] == target.

    Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.


     

    1. 첫 번째 풀이

     답을 반환할 리스트 answer를 생성 후 nums를 정렬한다. 그 후 enumerate 함수를 사용해 nums의 모든 요소의 인덱스와 값에 대해서 값이 target과 같다면 answer에 해당 인덱스를 더해준다. answer를 반환하면 끝!

    class Solution:
        def targetIndices(nums: List[int], target: int) -> List[int]:
            answer = []
            ordered_nums = sorted(nums)
            for idx, value in enumerate(nums):
                if value == target:
                    answer.append(idx)
            
            return answer

     

     

    2. 두 번째 풀이

     java로 풀었다. 역시 답을 반환할 리스트 answer를 생성 후 Arrays.sort()로 nums를 정렬한다. 그 후 IntStream의 range(0, nums.length)범위에서 nums[i]의 값이 target과 같은 i만 남도록 필터링한다. java에서는 int와 같은 원시 타입은 객체가 아니기 때문에 객체를 요구하는 제네릭에서 사용하려면 래퍼 클래스 객체로 변환해줘야 한다. 그 역할을 boxed()가 수행한다. 여기에 collect(Collectors.toList()) 로 스트림의 요소들을 리스트로 모은다.

     

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    class Solution {
    	public List<Integer> targetIndices(int[] nums, int target) {
        	List<Integer> answer = new ArrayList<>();
            Arrays.sort(nums);
            
            return IntStream.range(0, nums.length)
                   .filter(i -> nums[i] == target)
                   .boxed()
                   .collect(Collectors.toList<>());
        }
    }

     

     

    댓글

Designed by Tistory.