1.two_sum问题
解题思路,利用hashmap的特性,可以直接把对应数字的位置找出来,而不必轮询列表。
class Solution1 {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}
class Solution2 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
2.remove-duplicates
利用双指针,一个负责轮询,并对比前后两个数值是否一致,另一个负责插入,把不同的内容,插入到对应位置里。
class Solution1 {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
}
class Solution2 {
public int removeDuplicates(int[] nums) {
int n=1;
for(int i=1;i<nums.length;i++){
if(nums[i]!=nums[i-1]){
nums[n++]=nums[i];
}
}
return n;
}
}
3.remove element
利用对向的双指针,最多遍历一遍,在中间汇合就不用走了。
class Solution1 {
public int removeElement(int[] nums, int val) {
int n = nums.length;
int left = 0;
for (int right = 0; right < n; right++) {
if (nums[right] != val) {
nums[left] = nums[right];
left++;
}
}
return left;
}
}
class Solution2 {
public int removeElement(int[] nums, int val) {
int left = 0;
int right = nums.length;
while (left < right) {
if (nums[left] == val) {
nums[left] = nums[right - 1];
right--;
} else {
left++;
}
}
return left;
}
}