current position:Home>Delete the node in the linked list. There are duplicate elements

Delete the node in the linked list. There are duplicate elements

2021-08-27 03:32:45 DU777DU

Delete the nodes in the list

describe :

Please write a function , Make it possible to delete... Given in a linked list ( Not at the end ) node . The only parameter passed in to the function is   The node to be deleted  .

Ideas :

There is no head node , Therefore, you can't delete by pointing from the predecessor to the successor , Convert to delete node The way of subsequent nodes , Don't change the address, just change the value
(1) hold node Subsequent values are assigned to node
(2) hold node Subsequent set to node.next = node.next.next

Code :

class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
        
    }
}

There are duplicate elements

describe :

Given an array of integers , Determine whether there are duplicate elements .

If a value exists, it appears at least twice in the array , The function returns  true . If every element in the array is different , Then return to  false .

Ideas :

Reuse Set
(1) Special value processing
(2) establish HashSet
(3) Loop through groups , If the current element cannot be inserted , Represents the repetition of , return true
(4) The end of the loop means there is no , return false
 

Code :

class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums.length < 2) return false;
        HashSet<Integer> set = new HashSet<>();
        for(int num : nums){
            if(set.contains(num)){
                return true;
            }else{
                set.add(num);
            }
        }
        return false;
    }
}

copyright notice
author[DU777DU],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827033243629C.html

Random recommended