문제
숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.예를 들어,
nums = [3,2,3] return 3 nums = [2,2,1,1,1,2,2] return 2
가정
nums
배열의 길이는 무조건2
개 이상
key,value 형태로 만들자
{ "1" : 1의갯수 ,"2" : 2의갯수 ,"3" : 3의갯수 . . . } //ex) [ [ '1', 2 ], [ '2', 4 ], [ '3', 1 ] ]
function moreThanHalf(nums) { let obj = []; for (let num of nums) { // console.log(Object.keys(obj), typeof num); if (Object.keys(obj).includes(String(num))) { obj[num] += 1; } else { obj[num] = 1; } } console.log(Object.entries(obj)); let max = Object.values(obj)[0]; let maxKey = Object.keys(obj)[0]; for (const [key, value] of Object.entries(obj)) { console.log(max, key, value); if (value > max) { max = value; maxKey = key; } } return parseInt(maxKey); }
흠... 뭔가 더 간단한 방법이 있을거같긴한데...모르겠다 우선 1차원적으로 접근하여서 풀어보았다.
배운점
- 객체 내용 뽑아보기
Object.values(객체), Object.keys(객체), Object.entries(객체)
- 객체 내용으로 for문돌리기
for (const [key, value] of Object.entries(obj)) { . . . }