Skip to content

Instantly share code, notes, and snippets.

@ikhlaqmalik13
Last active July 7, 2023 10:20
Show Gist options
  • Save ikhlaqmalik13/13589974ccabd2a5fc83f65048fa6c5d to your computer and use it in GitHub Desktop.
Save ikhlaqmalik13/13589974ccabd2a5fc83f65048fa6c5d to your computer and use it in GitHub Desktop.
Blind75 Problems in java
import java.util.HashSet;
class DuplicateInList {
public static boolean doDuplicateExists(int[] arr){
HashSet<Integer> numbers = new HashSet<Integer>();
for(int i=0; i<arr.length; i++){
if(numbers.contains(arr[i])){
return true;
}
numbers.add(arr[i]);
}
return false;
}
public static void main(String[] args) {
int[] arr = {7, 1, 5, 3, 6, 4};
System.out.println(doDuplicateExists(arr));
}
}
public int findDuplicate(int[] nums) {
int slow = nums[0];
int fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = nums[0];
while(slow != fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
class Solution {
public int fib(int n) {
if(n <= 1){
return n;
}
int prev = 0;
int current = 1;
for(int i=2; i<=n; i++){
int next = prev + current;
prev = current;
current = next;
}
return current;
}
}
import java.util.HashMap;
class IndeciesOfTheTargetSumProblem {
public static int[] indeciesOfTarget(int target, int[] array){
int[] indecies = new int[2];
HashMap<Integer, Integer> numberNIndecies = new HashMap<>();
for(int i=0; i< array.length; i++){
int difference = target - array[i];
if (numberNIndecies.containsKey(difference)) {
indecies[0] = numberNIndecies.get(difference);
indecies[1] = i;
return indecies;
}
numberNIndecies.put(array[i], i);
}
return indecies;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int[] arr2 = indeciesOfTarget(4, arr);
System.out.println(arr2[0] + " " + arr2[1]);
}
}
class MaxProfitFromTheStockPrices {
public static int maxProfit(int[] arr) {
int buyPointer = 0;
int sellPointer = 1;
int maxProfit = 0;
while(sellPointer < arr.length){
if(arr[buyPointer] < arr[sellPointer]){
int profit = arr[sellPointer] - arr[buyPointer];
if(profit > maxProfit){
maxProfit = profit;
}
}else{
buyPointer = sellPointer;
}
sellPointer ++;
}
return maxProfit;
}
public static void main(String[] args) {
int[] arr = {7, 1, 5, 3, 6, 7, 4};
System.out.println(maxProfit(arr));
}
}
class Solution {
public int missingNumber(int[] nums) {
int arraySum =0;
int size = nums.length;
int formullaSum = (size * (size + 1))/2;
for(int num : nums){
arraySum += num;
}
return (formullaSum - arraySum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment