21 decembrie 2023

50 DSA-Questions: #3, #4

#3. Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
public class Exercise3 {
private final Integer[] NUMS = {5,2,21,8,4,12,9,19,1,13};

private void solve() {
Map<Integer, Integer> map = new HashMap<>();
for (int element : Arrays.asList(NUMS)) {
if (map.containsKey(element)) {
System.out.println("True");
return;
}
map.put(element, 0);
}
System.out.println("False");
}

public static void main(String args[]) {
new Exercise3().solve();
}
}

#4. Product of Array Except Self
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[I]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
public class Exercise4 {
// private final Integer[] NUMS = {1,2,3,4};
// private final Integer[] NUMS = {2,5,4,3,5};
private final Integer[] NUMS = {0};

private void solve() {
if (NUMS.length <= 1) {
System.out.println("Result N/A");
return;
}

Integer[] leftToRight = new Integer[NUMS.length];
leftToRight[0] = 1;
leftToRight[1] = NUMS[0];
for (int i=2; i<NUMS.length; i++) {
leftToRight[i] = leftToRight[i-1] * NUMS[i-1];
}

Integer[] rightToLeft = new Integer[NUMS.length];
rightToLeft[NUMS.length-1] = 1;
rightToLeft[NUMS.length-2] = NUMS[NUMS.length-1];
for (int i=NUMS.length-3; i>=0; i--) {
rightToLeft[i] = rightToLeft[i+1] * NUMS[i+1];
}

Integer[] result = new Integer[NUMS.length];
for (int i=0; i<NUMS.length; i++) {
result[i] = leftToRight[i] * rightToLeft[i];
}
System.out.println("Result = " + Arrays.asList(result));
// O(n)
}

public static void main(String args[]) {
new Exercise4().solve();
}
}

Niciun comentariu: