1.两数之和
两数之和https://leetcode-cn.com/problems/two-sum
//暴力枚举
class Solution {
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 Solution {
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.合并两个有序链表
合并两个有序链表https://leetcode-cn.com/problems/merge-two-sorted-lists/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}else if(l2 == null){
return l1;
}else if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l2.next,l1);
return l2;
}
}
}
3. 删除有序数组中的重复项
删除有序数组中的重复项https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
class Solution {
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;
}
}