본문 바로가기

Java/Java 알고리즘 LeetCode

[LeetCode- Ch.2 정렬 & 검색] 1. 제로 이동 (+ allMatch, noneMatch, for-while)

반응형

https://leetcode.com/problems/move-zeroes/submissions/

 

Move Zeroes - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

import java.util.*;
class Solution {
    public int[] moveZeroes(int[] nums) {
        //정수 배열에서 0이 아닌 값은 순서를 유지하고, 모든 0은 마지막으로 이동
        //배열 복사본 만들지 않고 수행
        
        //1.ds
        int n=nums.length;
        
        //2.loop
        //모두 0일 경우 바로 리턴
        //그 외엔 0이 아닌 개수를 구하고, 0이 아니면 [0]부터 채우기
        //0인 개수 만큼 [n-(0이 아닌 개수)]에 0채우기
        
        //(1) 모두 0인 경우 / 모두 0이 아닌 경우 바로 리턴
        if(Arrays.stream(nums).allMatch(a-> (a!=0))) return nums;
        else if(Arrays.stream(nums).noneMatch(a-> (a==0))) return nums;
        
        //(2) 모두 0은 아닌 경우 -> 0이 아닌 개수 구하기, 0이 아닌 값은 [0]부터 채운다.
        else{
            int k=0;
            int cnt=0;
            for(int i=0;i<n;i++){
                if(nums[i]!=0) cnt++;
            }
            for(int i=0;i<n;i++){
                if(nums[i]!=0){
                    nums[k++]= nums[i];
                }
            }
            
            //(3) 0인 개수 만큼 끝에 0채우기
            
            // 뒤에서 부터 0채우기
            // for(int i=n-1; i>=n-(n-cnt);i--){
            //     nums[i]=0;
            // }
            
            // 앞에서부터 0 채우기
            for(int i=n-(n-cnt);i<n;i++){
                nums[i]=0;
            }
            
        }
        return nums;
    }
}

 

자바 - 람다와 스트림

allMatch() 모든 요소가 조건에 충족하면 참
anyMatch() 최소한 한 개의 요소가 충족하면 참 
noneMatch() 모든 요소가 조건에 충족하지 않으면 참
public static void main(String[] args){
        int[] intArr = {2, 4, 6};

        boolean result = Arrays.stream(intArr)
                .allMatch(a -> a%2 == 0);

        result = Arrays.stream(intArr)
                .anyMatch(a -> a%3 == 0);

        result = Arrays.stream(intArr)
                .noneMatch(a -> a%3 == 0);
}

 

class Solution {
    public void moveZeroes(int[] nums) {
        //제로 이동
        //0이 아닌 값은 순서 유지, 0은 끝으로 이동
        int cnt=0;
        int n=nums.length;
        int index=0;
        for(int i=0; i<n;i++){
            if(nums[i]==0) {
                cnt++;
                continue;
            }
            nums[index++]=nums[i];
        }
        for(int j=n-1; j>=n-cnt;j--){
            nums[j]=0;
        }
    }
}

 

+) 세련된 코드1

(1) 0이 아니면, index에 값 넣기

(2) 덱스가 배열의 길이보다 작으면, 인덱스에 0 채우기

class Solution {
    public void moveZeroes(int[] nums) {
        //제로 이동
        //0이 아닌 값은 순서 유지, 0은 끝으로 이동
   	int index = 0;

		for (int i = 0; i < nums.length; i++) {
			if (nums[i] != 0) {
				nums[index] = nums[i];
				index++;
			}
		}
		while (index < nums.length) {
			nums[index] = 0;
			index++;
		}
		
	}
  
}

class Solution {
    public void moveZeroes(int[] nums) {
        int index=0;
        int n=nums.length;
        for(int i=0;i<n;i++){
            if(nums[i]!=0)
            nums[index++]=nums[i];
        }
        while(index<n){
            nums[index++]=0;
        }
    }
}
반응형