LeetCode算法题目(1)

171 阅读1分钟

1、反转链表

用迭代方法定义两个指针curr和prev,时间复杂度为O(n),空间复杂度为O(1);

class Solution{
    public ListNode reverseList(ListNode head){
         ListNode prev = null;
         ListNode curr = head;
        while(curr !=null){
             ListNode nextTemp = curr.next;
             curr.next = prev;
             prev = curr;
             curr = nextTemp;
        }
        return prev;
    }
}

2.两数之和:

创建一个哈希表,对于每一个x,我们首先查询哈希表中是否存在target - x,然后将x插入到哈希表中,即可保证不会让x和自己匹配

时间复杂度为O(n),n是数组中元素数量、空间复杂度与时间复杂度相同,主要为hash表开销;

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];
    }
}