Rotate Array - Leet Code Solution
Problem Statement Given an array, rotate the array to the right by k steps…
September 13, 2019
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
The obvious brute force algorithm. The key is to get the closest. You need to compare
Math.abs(target - calculated_sum)
Lets look at the optimized solution.
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int l = nums.length;
int minDiff = Integer.MAX_VALUE;
int result = 0;
for (int i=0; i<l; i++) {
int j=i+1;
int k=l-1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) return sum;
else if (sum < target) j++;
else k--;
if (Math.abs(target - sum) < minDiff) {
minDiff = Math.abs(target - sum);
result = sum;
}
}
}
return result;
}
Problem Statement Given an array, rotate the array to the right by k steps…
A Binary Search tree (BST) is a data structure which has two children nodes…
Problem Statement Write a function that reverses a string. The input string is…
Here are some tips while giving your coding interviews. 1. Never try to jump to…
Problem Statement Given two arrays, write a function to compute their…
This topic is one of the most common studied. When somebody started preparation…
Introduction This post has the complete code to send email through smtp server…
Introduction In a normal email sending code from python, I’m getting following…
Introduction In one of my app, I was using to talk to . I have used some event…
Introduction So you have a Django project, and want to run it using docker image…
Introduction It is very important to introduce few process so that your code and…
Introduction In this post, we will see a sample Jenkin Pipeline Groovy script…