leetcode小记3——array,string(238,242)

今天有点感冒了,有点难受,反应挺慢的好蠢。

238.Product of Array Except Self

 

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

首先题目里给了一个很明显的条件不能用除法。这个条件限制了很多常规的作法,但同时也有一个好处就是不用考虑除以0的情况。于是就考虑把乘的元素里面分为两部分,目标数的左边和右边两部分。

public class Solution {
    public int[] productExceptSelf(int[] nums) {
       int[] output = new int[nums.length];
       int temp = 1;
       output[0] = 1;
       for(int i = 1; i < nums.length; i++){
          temp *= nums[i-1];
          output[i] = temp;
       }  
       temp = 1;
       for(int i = nums.length-1; i > 0;i--){
           temp *= nums[i];
           output[i-1] *= temp;
       }
      
        return output;     
    }
}




242.Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

这道题首先要考虑几个点。第一就是字符串是没有序号的,于是想逐一比较的话就一定是要转换为数组,字符数组。

转换之后就可以把s内部的每个字母存在另一个数组里面,由于两个长度相同,因此只需要保证第二个在遍历数组的时候每一位的值都大于零即可。

public class Solution {
    public boolean isAnagram(String s, String t) {


        if(s.length() != t.length()) //this takes care of both null, one null and not the other also
            return false ; 




        //s and t need to have the same number of each letter
        //need a hashtable or each of them


        //only lowercase alphabets
        char[] s_char = s.toCharArray() ;
        char[] t_char = t.toCharArray() ; 




        //this is 4 to 5 ms soln better than about 90%


        int[] alphabet = new int[26] ; //only lower case alphabets


        for(int i = 0 ; i < t_char.length ; i++) {
            alphabet[t_char[i]-97]++ ; 
        }


        for(int i = 0 ; i < s_char.length ; i++) {
            if(alphabet[s_char[i]-97] > 0) //if what's there in t, is in s
                alphabet[s_char[i]-97]-- ; 
            else 
                return false ;
        }


        return true ;


    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值