Algorithm/java tip
Tip1(easy)
개구리는 개꿀개꿀
2020. 4. 5. 16:44
https://leetcode.com/problems/jewels-and-stones/
class Solution {
public int numJewelsInStones(String J, String S) {
int count=0;
for(int i=0;i<S.length();i++)
{
for(int j=0;j<J.length();j++)
{
if(S.charAt(i)==J.charAt(j))
count++;
}
}
return count;
}
}
String -> char array 변환 : String::toCharArray(), Character type for loop
class Solution {
public int numJewelsInStones(String J, String S) {
Set<Character> jSet = new HashSet<>();
for(int i=0; i < J.length(); i++) {
jSet.add(J.charAt(i));
}
int ans = 0;
for(int i=0; i < S.length(); i++) {
if(jSet.contains(S.charAt(i))) {
ans++;
}
}
return ans;
}
}
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] sort = new int[nums.length];
System.arraycopy(nums, 0, sort, 0, nums.length);
Arrays.sort(sort);
Map<Integer, Integer> sortMap = new HashMap<>();
int rank = 0;
for(int i : sort) {
sortMap.putIfAbsent(i, rank++);
}
int[] ans = new int[nums.length];
for(int i=0; i<nums.length; i++) {
ans[i] = sortMap.get(nums[i]);
}
return ans;
}
}
System::arraycopy / 대신에 int[] . clone() 이 더 쉬움
Arrays.sort
Map::putIfAbsent
https://leetcode.com/problems/decompress-run-length-encoded-list/submissions/
class Solution {
public int[] decompressRLElist(int[] nums) {
List<Integer> ans = new ArrayList<>();
for(int i=0; i<nums.length;i+=2) {
int freq = nums[i];
int val = nums[i+1];
for(int j=0; j<freq; j++) {
ans.add(val);
}
}
int[] ans2 = new int[ans.size()];
for(int i=0; i<ans.size(); i++) {
ans2[i] = ans.get(i);
}
return ans2;
}
}
ArrayList<Integer> <-> int[] 변환이 매우 불편함... 가능하면 둘중 하나만 사용하도록 하는게 좋을듯
ArrayList::add 는 Arrays.fill();로 대체 가능
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution {
public int subtractProductAndSum(int n) {
String strn = Integer.toString(n);
int mult = 1;
int sum = 0;
for(Character c : strn.toCharArray()) {
mult *= (c - '0');
sum += (c - '0');
}
return mult - sum;
}
}
https://leetcode.com/problems/create-target-array-in-the-given-order/
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
int[] target = new int[nums.length];
Arrays.fill(target, -1);
for(int i=0; i<nums.length; i++) {
if(nums[i] != -1) {
if (index.length - 1 - index[i] >= 0)
System.arraycopy(target, index[i], target, index[i] + 1, index.length - 1 - index[i]);
}
Arrays.fill(target, index[i], index[i] + 1, nums[i]);
}
return target;
}
}
System::arraycopy의 좋은 예