The order of elements can be changed. It doesn't matter what you leave beyond the new length.
You can just copy the elements instead of swapping.
Two pointers can both start from the first element.
Two time pass to one time pass
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
public int[] twoSum(int[] nums, int target) {
int [] res = new int [2];
if(nums.length < 2){
return res;
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])){
res[0] = map.get(target - nums[i]);
res[1] = i;
return res;
}
map.put(nums[i], i);
}
return res;
}
For a rotate problem, if given a point to rotate, consider k % length to avoid k > length
Think carefully when there are multiple conditions could quit the loop
public int longestConsecutive(int[] nums) {
if(nums.length <= 1){
return nums.length == 1 ? 1 : 0;
}
Arrays.sort(nums);
Set<Integer> set = new HashSet<Integer>();
int count = 1;
int max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++){
if(set.contains(nums[i])){
continue;
}
if(set.contains(nums[i] - 1)){
count++;
set.add(nums[i]);
}else {
set.add(nums[i]);
max = Math.max(max, count);
count = 1;
}
}
return Math.max(count, max);
}