Open sonic247897 opened 1 month ago
코드
class Solution {
public int findNumbers(int[] nums) {
int cnt = 0;
for (int i=0;i<nums.length;i++) {
int len = Integer.toString(nums[i]).length();
if (len %2 ==0) cnt++;
}
return cnt;
}
}
코드
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
int l = 0;
int r = len - 1;
int[] res = new int[len];
for (int i = len - 1; i >= 0; i--) {
if (Math.abs(nums[l]) > Math.abs(nums[r])) {
res[i] = (int) Math.pow(nums[l], 2);
l++;
} else {
res[i] = (int) Math.pow(nums[r], 2);
r--;
}
}
return res;
}
}
번외 (Arrays.sort() 를 이용하지 않고 TreeMap을 활용하여 정렬하였습니다)
class Solution {
public int[] sortedSquares(int[] nums) {
Map<Integer,Integer> map = new TreeMap<>();
for (int i=0;i<nums.length;i++) {
int square = (int)(Math.pow(nums[i],2));
int cnt = map.getOrDefault(square,0);
map.put(square,cnt+1);
}
int[] res = new int[nums.length];
int i=0;
for (Integer key : map.keySet()) {
int cnt = map.get(key);
for(int j=0;j<cnt;j++) res[i++] = key;
}
return res;
}
}
in-place
class Solution {
public void duplicateZeros(int[] arr) {
for (int i=0;i<arr.length-1;i++) {
if(arr[i]==0) {
for (int j=arr.length-1;j>i+1;j--) {
arr[j] = arr[j-1];
}
arr[i+1] = 0;
i++;
}
}
}
}
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i=0,j=0;
int[] res = new int[nums1.length];
for (int k=0;k<m+n;k++) {
if(i<m && j<n ){
if(nums1[i]<nums2[j]) {
res[k] = nums1[i];
i++;
}else {
res[k] = nums2[j];
j++;
}
}else if(j<n){
while(j<n){
res[k++]=nums2[j++];
}
break;
}else if(i<m){
while(i<m){
res[k++]=nums1[i++];
}
break;
}
}
for(int k=0;k<nums1.length;k++){
nums1[k] = res[k];
}
}
}
class Solution {
public int removeElement(int[] nums, int val) {
int cnt = 0;
int len = nums.length;
int k = len-1;
for (int i = 0; i < len; i++){
if(nums[i] == val) {
cnt++;
for(int j = k; j > i;j--) {
if (nums[j] != val) {
nums[i] = nums[j];
k = j - 1;
break;
}
}
}
}
return len-cnt;
}
}
class Solution {
public boolean checkIfExist(int[] arr) {
for (int i=0;i<arr.length;i++) {
for (int j=0;j<arr.length;j++) {
if (i==j) continue;
else if (arr[i]==2*arr[j]) return true;
}
}
return false;
}
}
코드
class Solution {
public int[] replaceElements(int[] arr) {
int[] max = new int[arr.length];
max[arr.length-1] = arr[arr.length-1];
for(int i=arr.length-2;i>=0;i--) {
max[i] = Math.max(arr[i],max[i+1]);
}
for (int i=0;i<arr.length-1;i++) {
arr[i] =max[i+1];
}
arr[arr.length-1]=-1;
return arr;
}
}
이번에만 PR을 봐주세요 😅
https://github.com/sonic247897/2024_algorithm_study/pull/2/files
가장 긴 연속한 1의 길이 찾기