Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3 sum problem in java program #185

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added LeetCode/JAVA/.DS_Store
Binary file not shown.
46 changes: 46 additions & 0 deletions LeetCode/JAVA/3sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.util.Arrays;

public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);

int rsum = nums[0] + nums[1] + nums[2];
int mindiff = Integer.MAX_VALUE;

for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;

while (left < right) {
int sum = nums[i] + nums[left] + nums[right;

if (sum == target) {
return target;
}

if (sum < target) {
left++;
} else {
right--;
}

int difftarget = Math.abs(sum - target);

if (difftarget < mindiff) {
rsum = sum;
mindiff = difftarget;
}
}
}

return rsum;
}

public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 4, 8, 16, 32};
int target = 26;
int result = solution.threeSumClosest(nums, target);
System.out.println("Closest sum to " + target + " is: " + result);
}
}