ARTS Week 11

Algorithm

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
int length = nums.length;
for (int first = 0; first < length - 1; first++) {
if (first > 0 && nums[first] == nums[first-1]) {
continue;
}
for (int second = first + 1; second < length; second++) {
if (second > first + 1 && nums[second] == nums[second-1]) {
continue;
}
int third = length - 1;
while (second < third && nums[first] + nums[second] + nums[third] > 0) {
third--;
}
if (second == third) {
break;
}
if (nums[first] + nums[second] + nums[third] == 0) {
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[first]);
tmp.add(nums[second]);
tmp.add(nums[third]);
ans.add(tmp);
}
}
}
return ans;
}
}

Review

#include <stdio.h>
#include <stdlib.h>
int main() {
size_t large = 1099511627776;
char *buffer = (char *)malloc(large);
if (buffer == NULL) {
printf("error!\n");
return EXIT_FAILURE;
}
printf("Memory allocated\n");
for (size_t i = 0; i < large; i += 4096) {
buffer[i] = 0;
}
free(buffer);
return EXIT_SUCCESS;
}

Tip

  1. Vector is thread safe, ArrayList is not thread safe.
  2. ArrayList expands the underlying array by 0.5 times when it is not enough, Vector expands it by 1 time.

Share

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KeepNewbie_yan

A programmer. Share knowledge of programming, operating system, Linux kernel, and reading, thinking etc. Let us maintain a beginner mend and grow together!