• leetcode day1


    【所有详解可以参考】http://tianmaying.com/tutorials/tag/Leetcode?filter=hot&page=1

    Two Sum:

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    解决思路:用一个map,for循环内,遍历数组中的加数1,map用来快速查询要找的加数2,如果找到,就返回map中的这个数,否则如果map没有此数,就put进去,key是数,value是数的index

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
    
            HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
            for(int i = 0; i < numbers.length; i++){
    
                Integer diff = (Integer)(target - numbers[i]);
                if(hash.containsKey(diff)){
                    int toReturn[] = {hash.get(diff)+1, i+1};
                    return toReturn;
                }
    
                hash.put(numbers[i], i);
    
            }
    
            return null;
    
        }
    }

    Remove Duplicates from Sorted Array:

    Given input array nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

    thought:

    用一个index洗刷掉数组中重复的元素,给数组重新赋值一遍,for循环遍历,当出现重复元素时,continue,否则,将下一个非重复的元素拿到前面来

    public class Solution {
        public int removeDuplicates(int[] nums) {
        if(nums.length<=1){
            return nums.length;
            
        }
        int index = 0;
        for(int i=0; i<nums.length;i++){
            if(nums[index]==nums[i]){
               continue; 
            }else{
               nums[++index]=nums[i];
            }
        }
        return index+1;
        /*Set testSet = new HashSet();
        for(int i = 0; i<nums.length ; i++){
           testSet.add(new Integer(nums[i]));
        }
        return testSet.size();*/
        }
    }
  • 相关阅读:
    BCP及自增标识列
    DAC重置max server memory
    登录名与用户名
    重复执行同一命令
    利用DBCC PAGE查看SQL Server中的表和索引数据
    索引约束
    JS高级程序设计笔记一
    div滚动底部加载li,window滚动底部加载li
    懂,才是最好的爱
    CSS3混合模式mix-blend-mode/background-blend-mode简介 ,PS中叠加效果
  • 原文地址:https://www.cnblogs.com/lucky-star-star/p/4950201.html
Copyright © 2020-2023  润新知